我有一个简单的Node.js中间件,我想测试一下它是否被正确处理。
简单的中间件
module.exports = (argumentOne, argumentTwo) => (req, res, next) => {
if (!argumentOne || !argumentTwo) {
throw new Error('I am not working');
};
req.requestBoundArgumentOne = argumentOne;
req.requestBoundArgumentTwo = argumentTwo;
next();
};
我想使用mocha,chai和sinon测试此中间件,但我根本不知道如何测试此内部功能。
我尝试了以下方法
describe('[MIDDLEWARE] TEST POSITIVE', () => {
it('should work', () => {
expect(middleware('VALID', 'TESTING MIDDLEWARE')).to.not.throw();
});
});
describe('[MIDDLEWARE] TEST NEGATIVE', () => {
it('shouldn\'t work', () => {
expect(middleware('INVALID')).to.throw();
});
});
在我的测试中,我知道这段代码是有效的,但仍会引发以下错误
AssertionError: expected [Function] to not throw an error but 'TypeError: Cannot set property \'requestBoundArgumentOne\' of undefined' was thrown
答案 0 :(得分:1)
通过查看您发布的代码,您的函数将返回另一个需要调用的函数。因此,测试应该以这种方式编写:
describe('middleware', () => {
let req, res, next;
beforeEach(() => {
// mock and stub req, res
next = sinon.stub();
});
it('should throw an error when argumentOne is undefined', () => {
const fn = middleware(undefined, 'something');
expect(fn(req, res, next)).to.throw();
});
it('should throw an error when argumentTwo is undefined', () => {
const fn = middleware('something', undefined);
expect(fn(req, res, next)).to.throw();
});
it('should call next', () => {
const fn = middleware('something', 'something');
fn(req, res, next);
expect(next.calledOnce).to.be.true;
});
});
要正确测试成功案例,您需要对req
和res
的值进行存根处理。