[英]Sinon - stubbing function with callback - causing test method to timeout
我在快速路線上有一個方法,如下所示:
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 onoutout](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 onoutout](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);
Sinon Stubs API在callsArg上有一些很好的文檔,還有一些callArgWith(這對你測試錯誤場景很有幫助)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.