node.jsモジュール内でいくつかの関数をユニットテストしたい。私は第3モジュールを嘲笑することが役に立つと思います。特に、これは私がポストに正しい体と、このURLを打つことは呼び出すことをテストすることができるようにしたいユニットテストのためのNode.jsのモジュールをモックする
# 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
をテストするモジュールであるデータベース
# 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
を打つ避けるために、 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()
を私はこれまでのところ(https://github.com/felixge/node-sandboxed-module、https://github.com/easternbloc/Syringe)Node.jsのためのいくつかのモックライブラリに見えたが、しています失敗。仕様で試してみると、いつもaccount.register
が実行されます。このアプローチ全体に欠陥がありますか?
は(https://github.com/arunoda/horaa) –
はsinon.jsを試してみてうまくいくかもしれない、優れたスタブ/スパイ/モック:ここでは私のためのサンプルユニットテストはどのように見えるかです/ mockServerライブラリ。 – nottinhill