测试 Express.js res.render 与 Mocha 和 Sinon 间谍的约定
Testing Express.js res.render within promise with Mocha & Sinon spy
遵循与 this example 类似的模式,我一直在尝试在 Express.js 应用程序中测试我的路由,但我无法让我的间谍验证 res.render
有包裹在 promise.then
.
中时被调用
这是一个简化的示例,我希望 calledOnce
为真,但返回的是假。
被测代码:
var model = {
get: function() {
return new Promise(function(res, rej) {
return res('success');
});
}
};
module.exports = function (req, res) {
model.get().then(function (data) {
res.render('home', data);
}).catch(function (err) {
console.log(err);
});
};
测试:
var expect = require('chai').expect;
var sinon = require('sinon');
var home = require('./home');
describe('home route', function() {
it('should return a rendered response', function() {
var req = {};
var res = {
render: sinon.spy()
};
home(req, res);
expect(res.render.calledOnce).to.be.true;
});
});
您必须等待承诺得到解决,这是一个异步操作。
由于 Mocha 原生支持 promise,您可以设置代码以将原始 promise 一直传递回 Mocha,并在链中插入测试用例:
// home.js
...
module.exports = function (req, res) {
// return the promise here
return model.get().then(function (data) {
res.render('home', data);
}).catch(function (err) {
console.log(err);
});
};
// test.js
describe('home route', function() {
it('should return a rendered response', function() {
var req = {};
var res = { render: sinon.spy() };
// Also return the promise here, and add an assertion to the chain.
return home(req, res).then(function() {
expect(res.render.calledOnce).to.be.true;
});
});
});
遵循与 this example 类似的模式,我一直在尝试在 Express.js 应用程序中测试我的路由,但我无法让我的间谍验证 res.render
有包裹在 promise.then
.
这是一个简化的示例,我希望 calledOnce
为真,但返回的是假。
被测代码:
var model = {
get: function() {
return new Promise(function(res, rej) {
return res('success');
});
}
};
module.exports = function (req, res) {
model.get().then(function (data) {
res.render('home', data);
}).catch(function (err) {
console.log(err);
});
};
测试:
var expect = require('chai').expect;
var sinon = require('sinon');
var home = require('./home');
describe('home route', function() {
it('should return a rendered response', function() {
var req = {};
var res = {
render: sinon.spy()
};
home(req, res);
expect(res.render.calledOnce).to.be.true;
});
});
您必须等待承诺得到解决,这是一个异步操作。
由于 Mocha 原生支持 promise,您可以设置代码以将原始 promise 一直传递回 Mocha,并在链中插入测试用例:
// home.js
...
module.exports = function (req, res) {
// return the promise here
return model.get().then(function (data) {
res.render('home', data);
}).catch(function (err) {
console.log(err);
});
};
// test.js
describe('home route', function() {
it('should return a rendered response', function() {
var req = {};
var res = { render: sinon.spy() };
// Also return the promise here, and add an assertion to the chain.
return home(req, res).then(function() {
expect(res.render.calledOnce).to.be.true;
});
});
});