8

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?

user3908406
  • 1,416
  • 1
  • 18
  • 32

2 Answers2

4

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 */
  });
Manu Artero
  • 9,238
  • 6
  • 58
  • 73
  • Worked great! One change though, the first line needs an '=', not a ':' let dateNowSpy = jest.SpyInstance; – C.T. Bell Aug 09 '22 at 19:44
  • @C.T.Bell I don't think that's correct, the code above is valid, it's declaring a variable of type `jest.SpyInstance` with an undefined value – JamesHalsall Mar 17 '23 at 10:16
  • @C.T.Bell this is ts code, it's declaring the type of `dateNowSpy` in pure js just suppress this declaration (-> `let dateNowSpy;`) – Manu Artero Mar 17 '23 at 11:24
4

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.

Gustavo Cesário
  • 1,310
  • 1
  • 12
  • 23