我在快速路线上有一个方法,如下所示:
exports.register_post = function(req, res) { var account = new Account(); account.firstName = req.param('firstName'); //etc... account.save(function(err, result) { email.sendOne('welcome', {}, function(err) { res.render('account/register', { title: 'Register' }); }); }); };
我有一个测试,我在那里email
跋涉.
email
是require
路线中的模块.
它有如下功能:
exports = module.exports.sendOne = function(templateName, locals, cb)
我的测试看起来像这样:
describe('POST /account/register', function(done) { var email; beforeEach(function(done) { accountToPost = { firstName: 'Alex', }; email = require('../../app/helpers/email'); sinon.stub(email) done(); }); afterEach(function(done) { email.sendOne.restore(); done(); }) it('creates account', function(done) { request(app) .post('/account/register') .send(this.accountToPost) .expect(200) .end(function(err, res) { should.not.exist(err) //todo: asserts done(); }); }); it('sends welcome email', function(done) { request(app) .post('/account/register') .send(this.accountToPost) .expect(200) .end(function(err, res) { should.not.exist(err) sinon.assert.calledWith(email.sendOne, 'welcome'); done(); }); }); });
当我运行测试时,都失败了,引用:
1)Controller.Account POST/account/register创建帐户:错误:超过2000ms超时为空.(/usr/local/lib/node_modules/mocha/lib/runnable.js:165:14)在Timer.listOnTimeout [as ontimeout](timers.js:110:15)
2)Controller.Account POST/account/register发送欢迎电子邮件:错误:超过2000ms超时为空.(/usr/local/lib/node_modules/mocha/lib/runnable.js:165:14)在Timer.listOnTimeout [as ontimeout](timers.js:110:15)
如果我email.sendOne('welcome', {}, function(err) {
在我的路线中注释掉,那么第一个测试(创建帐户)就会通过.
在设置我的sinon存根时我是否错过了什么?
Sinon存根不会自动触发任何回调函数,您需要手动执行此操作.尽管如此,它实际上是东方的:
describe('POST /account/register', function(done) { var email; beforeEach(function(done) { accountToPost = { firstName: 'Alex', }; email = require('../../app/helpers/email'); sinon.stub(email); email.sendOne.callsArg(2); done(); }); afterEach(function(done) { email.sendOne.restore(); done(); }) it('creates account', function(done) { request(app) .post('/account/register') .send(this.accountToPost) .expect(200) .end(function(err, res) { should.not.exist(err) //todo: asserts done(); }); }); it('sends welcome email', function(done) { request(app) .post('/account/register') .send(this.accountToPost) .expect(200) .end(function(err, res) { should.not.exist(err) sinon.assert.calledWith(email.sendOne, 'welcome'); done(); }); }); });
注意具体的行:
email.sendOne.callsArg(2);
该兴农存根API对callsArg一些好的文档,也callsArgWith(为你测试的错误情况可能是有用的)