Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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!"
        });
    });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda