Home > other >  Test serverless handler function in Next.js using Jest
Test serverless handler function in Next.js using Jest

Time:05-18

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.

CodePudding user 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!"
        });
    });
});
  • Related