我想在node.js模块中对一些函数进行单元测试 . 我认为嘲笑第3个模块会有所帮助 . 特别要避免命中数据库
# models/account.coffee
register = (email, password)->
sha_sum.update(password)
pw = sha_sum.digest('hex')
user =
email: email
password: sha_sum.digest('hex')
users_db.save user, (err, doc)->
register_callback(err)
account_module =
register: register
module.exports = account_module
这是我想测试的模块
# routes/auth.coffee
account = require '../models/account'
exports.auth =
post_signup: (req, res)->
email = req.body.email
password = req.body.password
if email and password
account.register(email, password)
res.send 200
else
res.send 400
我希望能够测试在帖子中调用 account.register
函数时使用正确的正文敲击此URL但我不希望测试命中数据库 . 我可能还没有实现帐户模块 .
茉莉花规格#specs / auth.test.coffee描述'注册', - >
request = require 'request'
it 'should signup a user with username and password', (done)->
spyOn(account, 'register') # this does not work, account.register still called
url = root + '/signup'
headers =
"Content-Type": "application/json"
data =
email: 'user@email.com'
password: 'pw'
body = JSON.stringify(data)
request {url: url, method: 'POST',json: data, headers: headers }, (err, response, body)->
expect(response.statusCode).toEqual(200)
done()
我已经查看了几个用于node.js(https://github.com/easternbloc/Syringe,https://github.com/felixge/node-sandboxed-module)的模拟库,但到目前为止还没有成功 . 无论我在规范中尝试什么, account.register
总是被执行 . 整个方法有缺陷吗?
3 回答
我使用mocha作为测试框架,sinon用于模拟,存根和 Spy . 我建议你将你的帐户模块委托给auth.coffee模块并像这样模拟它:
因此,从mocha测试中,您可以创建一个虚拟帐户对象,并在实际测试中使用sinon进行模拟 .
很抱歉没有把它写在coffescript中,但我不习惯 .
Stefan的解决方案有效 . 我只是添加一些细节 .
和
routes/auth.coffee
模块......我一直在使用gently进行模拟和存根,使用mocha进行测试框架,并使用should.js进行BDD样式的测试 . 以下是我对样本单元测试的样子: