我在快速路线上有一个方法,如下所示:
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
stub 。
email
是我在路由中需要
的模块。
它具有如下功能:
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 creates account: Error: timeout of 2000ms exceeded at null. (/usr/local/lib/node_modules/mocha/lib/runnable.js:165:14) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
2) Controller.Account POST /account/register sends welcome email: Error: timeout of 2000ms exceeded at null. (/usr/local/lib/node_modules/mocha/lib/runnable.js:165:14) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
如果我在路由中注释掉 email.sendOne('welcome', {}, function(err) {
,那么第一个测试(创建帐户)通过。
我在设置 sinon stub 时是否遗漏了什么?
最佳答案
Sinon stub 不会自动触发任何回调函数,您需要手动执行此操作。不过,这实际上真的很容易:
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);
Sinon Stubs API有一些关于 callsArg 和 callsArgWith 的很好的文档(这可能对您测试错误场景很有用)
关于javascript - Sinon - 带有回调的 stub 函数 - 导致测试方法超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307058/