Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
React - Test countdown component with jest (how to wait 1 second in jest when using setInterval)

I have a basic Countdown component based on react, and I want to write a suitable unit test for checking number changes. so far I tried two different ways, (the first one, is to tell jest I'm going to wait here so do not worry about time. and the second one, is to mock time changes). but none of them wasn't successful.

First approach:

describe('Test CountdownTimer component', () => {
   jest.setTimeout(60000);

   test('Shoud show current time 1 second later', async done => {
      const { getByText } = render(<CountdownTimer initialTime={10000} />);

      await act(async () => {
         await new Promise((r) => setTimeout(r, 1000));
      })
      expect(getByText('00:09')).toBeTruthy();
      
   });

});

Also tired:

describe('Test CountdownTimer component', () => {
   jest.setTimeout(60000);

   test('Shoud show current time 1 second later', async done => {
      const { getByText } = render(<CountdownTimer initialTime={10000} />);

      await new Promise((r) => setTimeout(r, 1000));
      expect(getByText('00:09')).toBeTruthy();
      
   });

});

Second approach:

describe('Test CountdownTimer component', () => {
   beforeEach(() => {
      jest.useFakeTimers();
   })

   test('Shoud show current time 1 second later', async done => {
      const { getByText } = render(<CountdownTimer initialTime={10000} />);
      act(() => {
         jest.advanceTimersByTime(1000);
      });
      expect(getByText('00:09')).toBeTruthy();
   });
});

// 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."

It's interesting that there isn't any comprehensive tutorial or well-detailed documentation about time-related tests in Jest. 🤔

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!