使用 JEST 模拟 Express 连锁响应

Kri*_*hna 2 node.js express typescript jestjs

我对笑话和打字稿很陌生,我正在尝试为笑话中的控制器功能创建一个小型单元测试

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;
Run Code Online (Sandbox Code Playgroud)

我为上述函数编写的单元测试是

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我收到错误

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

为什么我得到的是json未定义的,即使我嘲笑该属性?

bea*_*der 13

你的模拟需要一些调整:

const res = {} as unknown as Response;
res.json = jest.fn();
res.status = jest.fn(() => res); // chained
Run Code Online (Sandbox Code Playgroud)

正如 @hellitsjoe 指出的那样,Express 会连锁调用。

_res.status(200).json({ message: `Hello ${value}` })
Run Code Online (Sandbox Code Playgroud)

因此,您的模拟需要返回其他模拟才能使一切正常工作。