简体   繁体   中英

Test API route handler function in Next.js using Jest

I have the following health check function

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

and I have the following test

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);
  });
});

I want to check that the function is being called and that the status is 200, I know I need to mock out the function, however, how do I correctly mock out functions like this with a request and response.

The handler function accepts a res parameter that you can mock and pass to the handler call during the test. You can then verify the mocks have been properly called.

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!"
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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