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

211
Visualizações
Jest can't advance Timers

I'm trying to advance in time, I tried making this simple test:

it.only('Advance in time', async () => {
        console.log('primer clg', new Date(Date.now()).toISOString())

            jest.advanceTimersByTime(1000)

        console.log('segundo clg', new 
        Date(Date.now()).toISOString())
    })

But const pepe is always the same time... what I'm doing wrong? how can I advance in time?

console.log
    2022-04-06T19:08:12.795Z

  console.log
    2022-04-06T19:08:12.795Z

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

From the doc Advance Timers by Time:

jest.advanceTimersByTime(msToRun). When this API is called, all timers are advanced by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed.

This API is not used to fast forward Date. It's used for advanced the timers set by setTimeout() or setInterval()

For Date testing, you probably need to mock date, so that your test code does not depend on system time. Then you can run your test code in any CI/CD servers which have different OS and timezones.

You can call jest.fn().mockReturnValueOnce multiple times to mock different return values.

mockDate1 is the return value of the first call to Date.now(), mockDate2 is the return value of the second call to Date.now(). Both of them have fixed timestamps.

describe('first', () => {
  it('Advance in time', async () => {
    const mockDate1 = new Date(1649272092795);
    const mockDate2 = new Date(1649272092795 + 1_000);
    jest.spyOn(global.Date, 'now').mockReturnValueOnce(mockDate1).mockReturnValueOnce(mockDate2);
    console.log('primer clg', new Date(Date.now()).toISOString()); 
    console.log('segundo clg', new Date(Date.now()).toISOString());
  });
});

Test result:

 PASS  stackoverflow/71772373/index.test.js
  first
    ✓ Advance in time (14 ms)

  console.log
    primer clg 2022-04-06T19:08:12.795Z

      at Object.<anonymous> (stackoverflow/71772373/index.test.js:6:13)

  console.log
    segundo clg 2022-04-06T19:08:13.795Z

      at Object.<anonymous> (stackoverflow/71772373/index.test.js:7:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.867 s, estimated 1 s
about 4 years ago · Juan Pablo Isaza Relatório
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