'Jest: setSystemTime is not available when not using modern timers

Here is the code. I'm getting error TypeError: setSystemTime is not available when not using modern timers when I run the test. I have "@jest/fake-timers": "^27.4.2" in my package.json since I thought there could be a conflict on the package in some dependencies, but issue remains

beforeAll(() => {
    jest.useFakeTimers('modern');
    jest.setSystemTime(new Date());
});

afterAll(() => {
    jest.useRealTimers();
});

Any idea how to resolve this?



Solution 1:[1]

Facing the same issue here, this patch from @stereodenis is working (copying it here):

let dateNowSpy: jest.SpyInstance;
const today = new Date('2000-01-01').getTime();

describe('...', () => {
  beforeEach(() => {
    dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => today);
  });

  afterEach(() => {
    dateNowSpy.mockRestore();
  });

  test('...', () => {
    /* Date.now() -> 2000-01-01 */
  });

Solution 2:[2]

As mentioned in this issue, it can be solved by checking the version of jest and it's related packages. For example, I had jest on version 26.6.0 and babel-jest and ts-jest on 27.x. Setting them to 26.x solved the problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manu Artero
Solution 2 Gustavo Cesário