How to Test NextJS page with Dynamic Route Using Jest

Assuming we have a API route with api/[id]/data

First install required library node-mocks-http

yarn add --dev node-mocks-http

Next we use createMocks to create a req and res object.

import data from "../pages/api/[id]/data";
import { createMocks } from "node-mocks-http";
describe("API Endpoint Tests", () => {
    it("Data", async () => {
        const { req, res } = createMocks({
            method: "GET",
            query: { id: 1000 }, //Here you enter all your dynamic route values
        });
        await data(req, res);
        expect(res._getStatusCode()).toBe(200);
        expect(JSON.parse(res._getData())).toHaveProperty("response");
    });
});
export {};

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *