我有一个演示功能:
export async function myHandler(
param1: string,
param2: string,
req: Request,
next: NextFunction,
) {
const log = req.log.prefix(`[my=prefix]`);
let res;
If (param1 === 'param1') {
log("GOT PARAM 1");
} else {
res = await doSomething();
}
log("GOT HERE");
..
..
..
..
res.setReturnStatus(200)
}
next();
}
对于记录器,这是包含它的请求:
const req: {
url: string;
params: {};
body: {
device: {
type: string;
p1: string;
p2: string;
p3: string;
};
data: {
sample: number;
};
};
metric: () => jest.Mock<any, any>;
log: {
(): jest.Mock<any, any>;
warn(): jest.Mock<...>;
error(): jest.Mock<...>;
prefix(): jest.Mock<...>;
};
timing: () => jest.Mock<...>;
}
当我编写单元测试时,我的行是检查返回状态:expect(res.status).toBeCalledWith(200);
我想涵盖第一个'if‘语句,其中的日志’获得PARAM 1‘,但不知道如何拦截我的电话在中间。
doSomething = jest.fn(() => Promise.resolve());
await myHandler('param1', 'param1', next); //HERE to check somehow that also was log ?
expect(res.status).toBeCalledWith(200);
试图做这样的事情:
const spy = jest.spyOn(req.log, 'log');
得到了错误:
Cannot spy the log property because it is not a function; undefined given instead
发布于 2020-06-04 09:46:58
由于log
起源于req
,所以应该通过它传递模拟的实现:
let mockLog = jest.fn();
let mockReq = { log: { prefix: jest.fn().mockReturnValue(mockLog) } };
await myHandler('param1', 'param1', mockReq, next);
expect(mockReq.log.prefix).toBeCalledWith(...);
expect(mockLog).toBeCalledWith(...);
这一尝试失败是因为它是req.log.prefix
,而不是req.log.log
const spy = jest.spyOn(req.log, 'log');
https://stackoverflow.com/questions/62189004
复制相似问题