author avatar

amber.srivastava

Thu Sep 26 2024

How to test an API endpoint.

Let's say we have to test an endpoint /api/projects.

describe("POST /api/projects", () => {
    test("redirect with 401 status if the user is not logged in", async () => {
      jest
        .spyOn(nextAuth, "getServerSession")
        .mockImplementation(() => Promise.resolve());

      const req = createRequest<APIRequest>({
        method: "POST",
        url: "/api/projects",
        body: projectData,
      });

      const res = await postProjectHandler(req as any);
      expect(res.status).toEqual(401);
    });

    test("return 400 if the request body is invalid", async () => {
      jest.spyOn(nextAuth, "getServerSession").mockImplementation(() =>
        Promise.resolve({
          user: {
            id: user.id,
          },
        })
      );

      const req = createRequest<APIRequest>({
        method: "POST",
        url: "/api/projects",
        body: {},
      });

      req.json = jest.fn().mockResolvedValue(req.body);

      const res = await postProjectHandler(req as any);

      expect(res.status).toEqual(400);
    });

    test("store project in database", async () => {
      jest.spyOn(nextAuth, "getServerSession").mockImplementation(() =>
        Promise.resolve({
          user: {
            id: user.id,
          },
        })
      );

      const mockResponse = {
        ok: true,
        team: {
          id: "T08DABCD",
          name: "Prisma",
        },
      };

      const mockList = jest.fn().mockResolvedValue(mockResponse);
      <http://slackClient.team.info|slackClient.team.info> = mockList;

      const req = createRequest&lt;APIRequest&gt;({
        method: "POST",
        url: "/api/projects",
        body: {
          ...projectData,
        },
      });

      req.json = jest.fn().mockResolvedValue(req.body);

      const res = await postProjectHandler(req as any);
      const json = await res.json();

      expect(res.status).toEqual(201);
      expect(json.project.name).toEqual("Test name");
      expect(json.project.description).toEqual(
        "Test description"
      );
    });
  });