测试中间件的 JS 返回 next()



我有一个这样的中间件类

// code.js
function validation(req, res, next) {
if (validationLogic(req)) {
res.send(400);
return next(false);
}
return next();
}
// code.test.js
describe('validation', () => {
describe('when req is valid', () => {
//setting up req, res, next stub
//some other test
//HERE IS MY QUESTION, how do I text that validation returns next(), and not next(false)
it('return next(), and next() is called exactly once', () => {
const spy = sinon.spy();
nextStub = spy;
const result = validation(reqStub, resStub, nextStub);
assert(spy.calledOnceWithExactly());
assert(result === nextStub()); // both of this
assert(result === nextStub(false)); // and this line passed
});
});
});

我试图测试我的validation函数是否返回next()而不是next(false)。但是在测试中,似乎只有assert(spy.calledOnceWithExactly())才能在next中测试参数。但是assert(result === nextStub())后面的行不能测试任何内容,除了结果实际上来自函数next()

assert(spy.calledOnceWithExactly())是否足够,或者有没有其他方法可以测试它?

你不需要使用间谍。 您始终可以创建一个接受参数并将其替换为 next 的"占位符"函数,并确保该函数不会返回false

it('return next(), and next() is called exactly once', () => {
const nextStub = (arg) => (arg === false ? arg : 'I was called!');
const result = validation(reqStub, resStub, nextStub);

assert(result !== false);
assert(result === 'I was called!');
});

这样的事情可能会奏效。或者,如果您真的想使用间谍,则可以检查间谍的返回值以及间谍的调用方式。确保您的间谍功能可以接受参数。

https://sinonjs.org/releases/v7.0.0/spy-call/

解决此问题的一种干净方法是使用expectation来验证是否使用确切的参数调用了一次next,并且结果是否从validation返回:

it('return next(), and next() is called exactly once', () => {
const expectation = sinon.mock().once().withExactArgs().returns('called with no args');
nextStub = expectation;
const result = validation(reqStub, resStub, nextStub);
expectation.verify();  // SUCCESS
assert(result === 'called with no args');  // SUCCESS
});

最新更新