我具有用于将所有故障直接传递给快速错误处理程序的功能。我正在为此编写测试,并且试图通过正确传递函数正确地测试它。
asyncHandlerUtil.js
const asyncHandlerUtil = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
module.exports = asyncHandlerUtil;
现在我有(意识到这是错误的atm)
asyncHandlerUtil.spec.js
import asyncHandlerUtil from './asyncHandlerUtil';
describe('Given the asyncHandlerUtil function', () => {
describe('when is is called', () => {
let middleware;
let fn;
let subFn;
beforeEach(() => {
subFn = jest.fn();
fn = jest.fn(() => subFn);
middleware = asyncHandlerUtil(fn);
middleware();
});
it('should call fn', () => {
expect(fn).toHaveBeenCalledWith(subFn);
});
// other tests needed for rejection and catching errors.
});
});
谢谢!
这里是单元测试解决方案:
asyncHandlerUtil.js
:
const asyncHandlerUtil = (fn) => (req, res, next) => {
return Promise.resolve(fn(req, res, next)).catch(next);
};
module.exports = asyncHandlerUtil;
asyncHandlerUtil.test.js
:
const asyncHandlerUtil = require('./asyncHandlerUtil');
describe('62063369', () => {
it('should pass', async () => {
const mFn = jest.fn().mockResolvedValueOnce('mocked value');
const mReq = {};
const mRes = {};
const mNext = jest.fn();
const got = await asyncHandlerUtil(mFn)(mReq, mRes, mNext);
expect(got).toBe('mocked value');
expect(mFn).toBeCalledWith({}, {}, mNext);
});
});
带有覆盖率报告的单元测试结果:
PASS stackoverflow/62063369/asyncHandlerUtil.test.js (12.14s)
62063369
✓ should pass (5ms)
---------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
asyncHandlerUtil.js | 100 | 100 | 100 | 100 |
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.218s