JEST模拟快速链接响应



我对jest和typescript很陌生,我正在尝试为jest 中的控制器函数创建一个小单元测试

import { Request, Response } from 'express';
const healthCheck = (_req: Request, _res: Response) => {
const value = _req.params.name ?? 'World!';
return _res.status(200).json({ message: `Hello ${value}` });
};
export default healthCheck;

我为上述功能编写的单元测试是

import { Request, Response } from 'express';
import healthCheck from './health.controller';
describe('Health Controller', () => {
it('healthCheck should send 200 on an optional path param', () => {
const req = { params: {} } as Request;
const res = {
json: jest.fn(),
status: jest.fn(),
} as unknown as Response;
healthCheck(req, res);
expect(res.status).toHaveBeenCalledWith(200);
});
});

我收到一个错误

TypeError: Cannot read property 'json' of undefined
>  8 |   return _res.status(200).json({ message: `Hello ${value}` });

为什么我得到未定义的json,即使我模拟这个属性?

你的模拟需要一点调整:

const res = {} as unknown as Response;
res.json = jest.fn();
res.status = jest.fn(() => res); // chained

正如@hellitsjoe所指出的,Express将呼叫连锁。

_res.status(200).json({ message: `Hello ${value}` })

所以你的mock需要返回其他mock才能使一切正常工作。

由于您正在调用res.status().json(),因此json应该是status()的返回值上的函数,而不是res上的函数。

这种类型的嘲讽的一个流行库是node-mocks-http,它为您提供了传递到处理程序中的reqres对象,这样您就不必自己嘲笑它们了。

最新更新