0

I have a test usinging jest thats try to validate an result of a http request to an endpoint (nextjs) which results in a timeout depending on the input parameters like: "/timeout/300"

this is the test https://github.com/Streeterxs/timeout-server/blob/main/src/app/api/timeout/%5Bms%5D/__tests__/%5Bms%5D.spec.ts#L18

// why this is not working?
it.skip("Should successfully timeout for 300ms", async () => {

  const ms = '300';
  const params: Record<string, string | string[]> = {ms};

  const testApiHandlerPromise = testApiHandler({
    appHandler: timeoutRouteHandler,
    params,
    test: async ({ fetch }) => {

      const responsePromise = fetch({ method: "GET" });

      // https://stackoverflow.com/questions/51126786/jest-fake-timers-with-promises
      jest.runAllTimers();
      const response = await responsePromise;

      const json = await response?.json();

      console.log({json})
      expect(response.status).toBe(200);
      expect(json).toStrictEqual({
        error: null,
        success: `Timeouted ${ms}ms`
      });
      expect(setTimeout).toHaveBeenCalledTimes(1);
    },
  });

  // https://stackoverflow.com/questions/51126786/jest-fake-timers-with-promises
  // dont know if this is needed, but since this promise runs inside the package scope I tried it out
  // probably occurs because of the callback code of test function
  // but I tried to modify the code and it stuck right on the setTimeout function
  jest.runAllTimers();

  await testApiHandlerPromise;
});

yes, Im using a package that encapsulates the test Im trying todo. It justs executes the global fetch function in a way that nextJs understands it (at least it was what I undestood)

Already tried the differents solutions that deals with setTimeout + promises out there but none worked (I think it is because the promise is encapsulated in a http request dont know for sure but it would be cool if anyone answers that too)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.