Jest: setSystemTime is not available when not using modern timers

Viewed 3059

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?

2 Answers

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.

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 */
  });
Related