Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda