当回调未作为参数传递时,如何使用sinon在node.js中对回调进行单元测试?
我如何在Node.js(express.js)中对上述函数进行单元测试,尤其是在回调没有作为参数传入时?我计划使用Sinon单元测试框架当回调未作为参数传递时,如何使用sinon在node.js中对回调进行单元测试?,node.js,unit-testing,sinon,Node.js,Unit Testing,Sinon,我如何在Node.js(express.js)中对上述函数进行单元测试,尤其是在回调没有作为参数传入时?我计划使用Sinon单元测试框架 此处显示的示例:仅显示如何在回调作为参数传递时进行测试。基本上,我们可以在单元测试中进行一些检查: 检查req.headers[constants.DATA]的值是否正确 检查是否调用了next 下面是我的一个例子来测试代码 var data = function (req, res, next) { var data; modelClass.
此处显示的示例:仅显示如何在回调作为参数传递时进行测试。基本上,我们可以在单元测试中进行一些检查:
req.headers[constants.DATA]
的值是否正确next
var data = function (req, res, next) {
var data;
modelClass.getData(function (err, response) {
data = response[0];
req.headers[constants.DATA] = data;
next();
}
});
};
这个问题有点宽泛,因为您可以测试这个问题的几个不同方面。这个想法应该不会太坏,因为您可以将自己的
next()
和req
传入。
const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');
const modelClass = require('...'); // your model class file
const src = require('...'); // your source file
describe('test', function() {
let req;
let res;
let next;
const response = [100];
beforeEach(function() {
// we mock `req` and `next` here
req = {
headers: {}
};
next = sinon.spy();
sinon.stub(modelClass, 'getData').yields(null, response); // for callback function, we use yields to trigger the callback
});
afterEach(function() {
sinon.restore();
})
it('run successfully', function() {
src.data(req, res, next);
assert.equal(req.headers[constants.DATA], 100);
assert(next.calledOnce);
});
});