Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda