在node.js中对单元测试中的依赖项进行存根

时间:2012-12-02 17:14:28

标签: unit-testing node.js mocking mocha stub

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

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

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

由于

1 个答案:

答案 0 :(得分:1)

许多node.js项目中的当前模块组合似乎是:

  • Mocha用于实际测试工具本身
  • Chai用于断言
  • Sinon用于模拟/存根

所有这些都在node.js和浏览器中都有效,这对包括我自己在内的很多人来说很重要。有许多选择可供选择,但是当涉及到模拟和剔除时,我相信Sinon显然是当前流行的选择。

这是coffeescript中使用所有这些库的一个小例子。它测试当您填写登录表单并提交时,您的信息将正确传递给API。

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