我想單元測試node.js模塊中的一些函數。我認爲嘲笑第三個模塊會有所幫助。特別要避免撞上數據庫在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
我希望能夠測試擊中在後這個網址與正確的身體調用的模塊account.register
函數,但我不想測試打到數據庫。我可能還沒有實施帳戶模塊。
茉莉花規範 #規格/ 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: '[email protected]'
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
總會得到執行。這整個方法是否有缺陷?
它看起來像horaa(https://github.com/arunoda/horaa)可能工作 –
嘗試sinon.js,一個優秀的存根/間諜/模擬/ mockServer庫。 – nottinhill