![](/img/trans.png)
[英]How to mock or stub 'instanceof' in Chai | Sinon | Mocha
[英]How to mock, and test, closures with mocha, chai and sinon
我有一個簡單的 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();
});
});
在我的 TEST POSITIVE 中,我知道此代碼有效,但仍會引發以下錯誤
AssertionError: expected [Function] to not throw an error but 'TypeError: Cannot set property \'requestBoundArgumentOne\' of undefined' was thrown
通過查看您發布的代碼,您的函數返回了另一個需要調用的函數。 所以測試應該這樣寫:
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
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.