var data = function (req, res, next) {
var data;
modelClass.getData(function (err, response) {
data = response[0];
req.headers[constants.DATA] = data;
next();
}
});
};
我如何在Node.js(express.js)中对上述功能进行单元测试,尤其是当回调不作为参数传递时?我计划使用Sinon单元测试框架。
此处显示的示例:youtube tutorial仅显示如何测试将回调作为参数传递的情况。
答案 0 :(得分:1)
基本上,我们可以在单元测试中进行一些检查:
req.headers[constants.DATA]
的值是否正确next
这是我的示例来测试该代码
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);
});
});