Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I use jest fake timers when testing code that use p-queue? #193

Open
bluprince13 opened this issue Aug 10, 2023 · 1 comment
Open

Comments

@bluprince13
Copy link

I am trying to test my code that makes use of p-queue.

However, I don't want my test to actually wait for seconds. I tried to use https://jestjs.io/docs/timer-mocks.

jest.useFakeTimers();

I also tried to mock setTimeout myself

       const setTimeoutCopy = setTimeout
       let waitingTime = 0
       jest.spyOn(global, "setTimeout").mockImplementation((f, ms) => {
            waitingTime += ms
            return setTimeoutCopy(f, 0)
        })

However, this seems to have no effect on p-queue.

And my test times out with:

Error: thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

Would appreciate some guidance.

@arantespp
Copy link

arantespp commented Jul 2, 2024

I solved this following this recommendation.

I've removed await from my method and added await jest.runAllTimersAsync(); await flushPromises();

const flushPromises = () => {
  // Wait for promises running in the non-async timer callback to complete.
  // From https://stackoverflow.com/a/58716087/308237
  return new Promise((resolve) => {
    return setImmediate(resolve);
  });
};

test('my test', async () => {  
  myAsyncMethod();

  await jest.runAllTimersAsync();

  await flushPromises();

  expect(true).toBe(true);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants