我想对一个node.js模块中的一些函数进行单元测试。 我认为模拟第三个模块会很有帮助,特别是避免访问数据库。
# 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
我希望能够测试在正确的post body下访问此url是否调用了account.register
函数,但我不想进行与数据库的交互测试。也许我还没有实现账户模块。
jasmine规范 # specs/auth.test.coffee describe 'signup', ->
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),但是迄今为止没有成功。无论我在规范(spec)中尝试什么,account.register
总是会被执行。这种方法是否有缺陷?