Skip to content

When using waitFor the jest.setSystemTime is reset to actual system time #1001

Closed
@coreyjv

Description

@coreyjv

What you did:

Attempting to use fake timers and assert those dates and times after using waitFor

What happened:

The system time was reset to the current time after waitFor.

Reproduction:

import { render, screen, waitFor } from '@testing-library/react';

beforeEach(() => {
  jest.useFakeTimers('modern');
  jest.setSystemTime(new Date("2023-02-18"));
})

afterEach(() => {
  jest.runOnlyPendingTimers()
  jest.useRealTimers()
})

test('test the fake timer', async () => {
  render((<p>text</p>));

  await waitFor(() => screen.getByText('text'))

  expect(new Date().getFullYear()).toEqual(2023)
});

Problem description:

Test results:

  ● test the fake timer

    expect(received).toEqual(expected) // deep equality

    Expected: 2023
    Received: 2021

      16 |   await waitFor(() => screen.getByText('text'))
      17 |
    > 18 |   expect(new Date().getFullYear()).toEqual(2023)
         |                                    ^
      19 | });
      20 |

When using waitFor it appears that the system time that was set using Jest's fake timers was reset to the current time. If you remove the waitFor the test passes as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions