我想对 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
我希望能够测试在帖子中使用正确的正文点击此 url 调用该account.register
函数,但我不希望测试点击数据库。我可能还没有实现 account 模块。
jasmine 规范 #specs/auth.test.coffee 描述 '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),但到目前为止没有成功。无论我在规范中尝试什么,account.register
总是会被执行。这整个方法有缺陷吗?