Javascript ';Express.js异步处理程序';-为it编写测试有困难
我使用这个函数将任何失败直接传递给express错误处理程序。我正在为它编写测试,我正在努力思考如何通过正确地传递函数来正确地测试它 asynchHandlerUtil.jsJavascript ';Express.js异步处理程序';-为it编写测试有困难,javascript,reactjs,unit-testing,express,jestjs,Javascript,Reactjs,Unit Testing,Express,Jestjs,我使用这个函数将任何失败直接传递给express错误处理程序。我正在为它编写测试,我正在努力思考如何通过正确地传递函数来正确地测试它 asynchHandlerUtil.js const asyncHandlerUtil = fn => (req, res, next) => { return Promise .resolve(fn(req, res, next)) .catch(next); }; module.exports = asyn
const asyncHandlerUtil = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
module.exports = asyncHandlerUtil;
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.
});
});
现在我已经(意识到它错了)
asynchHandlerUtil.spec.js
const asyncHandlerUtil = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
module.exports = asyncHandlerUtil;
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.
});
});
谢谢 以下是单元测试解决方案:
asynchHandlerUtil.js
:
const asynchHandlerUtil=(fn)=>(req,res,next)=>{
返回Promise.resolve(fn(req,res,next)).catch(next);
};
module.exports=asyncHandlerUtil;
asynchHandlerUtil.test.js
:
const asynchHandlerUtil=require('./asynchHandlerUtil');
描述('62063369',()=>{
它('should pass',async()=>{
const mFn=jest.fn().mockResolvedValueOnce(“模拟值”);
常量mReq={};
常数mRes={};
const mNext=jest.fn();
const got=等待AsynchHandlerUtil(mFn)(mReq、mRes、mNext);
expect(got).toBe(“模拟值”);
期望(最惠国)与({},{},mNext)合并;
});
});
单元测试结果和覆盖率报告:
PASS stackoverflow/62063369/asynchHandlerutil.test.js(12.14s)
62063369
✓ 应通过(5ms)
---------------------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
---------------------|---------|----------|---------|---------|-------------------
所有文件| 100 | 100 | 100 | 100 |
asyncHandlerUtil.js | 100 | 100 | 100 | 100 |
---------------------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:14.218s
您需要考虑一下这里实际发生了什么fn
是asynchHandlerUtil
的参数;这应该是一个返回模拟函数的模拟函数,这与fn
实际交互的方式一致吗expected
是来自asynchHandlerUtil
的返回;这是中间件,在调用之前不会发生任何事情。还有expect(fn)。toHaveBeenCalledWith(subFn)
期望fn
被调用并返回它所返回的东西,这似乎是不可信的。