1

我从 node.js 单元测试开始,我一直在研究 node.js 中最常用的单元测试框架。我想从最常用的框架开始,只是为了让事情变得更容易,因为可能有更多关于它的信息。根据许多可能是摩卡的网站。

虽然我了解这个模块用于进行集成测试,但我真的不知道如何通过使用诸如存根依赖项之类的功能来使用它。我见过 mocha 不提供模拟/存根功能,所以我真的不知道人们通常如何处理这些问题。

所以我想知道现在哪些模块最流行用于进行单元测试,存根依赖项......一个简短的例子会很棒。

谢谢

4

1 回答 1

1

The current suite of modules combined together in many node.js projects seems to be:

  • Mocha for the actual test harness itself
  • Chai for assertions
  • Sinon for mocking/stubbing

All of these work both in node.js as well as the browser, which is important to many people including myself. There are many choices available as you might expect, although when it comes to mocking and stubbing I believe Sinon is clearly the current popular choice.

Here's a small example in coffeescript that uses all of these libraries. It tests that when you fill in the sign in form and submit it, your info is passed to the API properly.

describe "UserSignInView.signIn", ->
  it "should submit the user credentials", ->
    sinon.spy _OT.api, "sendJSON"
    testUser =
      email: "test.user@othenticate.com"
      password: "password"
    $("#OT_signInForm .OT_email").val(testUser.email).change()
    $("#OT_signInForm .OT_password").val(testUser.password).change()
    $("#OT_signInForm .OT_signInButton").click()
    assert.ok _OT.api.sendJSON.called
    credentials = _OT.api.sendJSON.lastCall.args[0]
    assert.equal credentials.email, testUser.email
    assert.equal credentials.password, testUser.password
    options = _OT.api.sendJSON.lastCall.args[1]
    assert.equal options.url, "/othen/users/authenticate"
    assert.isDefined options.error
    assert.isDefined options.success
于 2012-12-02T17:32:06.690 回答