繁体   English   中英

使用 Jest 在 Next.js 中测试 API 路由处理函数

[英]Test API route handler function in Next.js using Jest

我有以下健康检查功能

export default function handler(req, res) {
  res.status(200).json({ message: "Hello from Next.js!" });
}

我有以下测试

import handler from "./healthcheck"

describe("Healthcheck", () => {
  test("that the application is live with a status of 200", () => {
    const mockFn = jest.fn({
      status: jest.fn(),
      json: jest.fn()
    });

    expect(mockFn).toHaveBeenCalledWith();
    expect(mockFn.status).toBe(200);
  });
});

我想检查该函数是否正在被调用并且状态为 200,我知道我需要模拟该函数,但是,我如何正确地模拟这样的带有请求和响应的函数。

handler函数接受一个res参数,您可以在测试期间模拟并传递给handler调用。 然后,您可以验证已正确调用模拟。

import handler from "./healthcheck"

describe("Healthcheck", () => {
    test("that the application is live with a status of 200", () => {
        const resMock = { status: jest.fn() }; // Mocks `res`
        const resStatusMock = { json: jest.fn() }; // Mock `res.status`
        resMock.status.mockReturnValue(resStatusMock); // Makes `res.status` return `resStatusMock`
        
        handler(undefined, resMock);

        expect(resMock.status).toHaveBeenCalledWith(200);
        expect(resStatusMock.json).toHaveBeenCalledWith({
            message: "Hello from Next.js!"
        });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM