【问题标题】:Stubbing dependencies in unit tests in node.js在 node.js 中的单元测试中存根依赖项
【发布时间】:2012-12-03 01:32:06
【问题描述】:
我从 node.js 单元测试开始,我一直在研究 node.js 中最常用的单元测试框架。我想从最常用的框架开始,只是为了让事情变得更容易,因为可能有更多关于它的信息。根据许多可能是摩卡的网站。
虽然我了解这个模块用于进行集成测试,但我真的不知道如何通过使用诸如存根依赖项之类的功能来使用它。我看到 mocha 不提供模拟/存根功能,所以我真的不知道人们通常如何处理这些问题。
所以我想知道现在哪些模块最流行用于进行单元测试、存根依赖项......一个简短的例子会很棒。
谢谢
【问题讨论】:
标签:
unit-testing
node.js
mocking
mocha.js
stub
【解决方案1】:
目前在许多 node.js 项目中组合在一起的模块套件似乎是:
所有这些都可以在 node.js 和浏览器中使用,这对包括我自己在内的许多人都很重要。正如您所料,有很多选择可供选择,但在嘲笑和存根方面,我相信 Sinon 显然是当前流行的选择。
这是一个使用所有这些库的咖啡脚本中的小示例。它测试当您填写登录表单并提交时,您的信息是否正确传递给 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