3

I am mocking Date.now() implementation returning a specific date however, after the test is done the afterAll + mockRestore() doesn't quite rid of the mock.

When I run another test the date now is still mocked to 1626764400000. Is there a different function I have to use to reset the mock? I have already used: mockReset, mockClear, jest.clearAllMocks.

beforeAll((): void => {
  jest.spyOn(Date, 'now').mockImplementation(() => 1626764400000);
});

afterAll((): void => {
  jest.clearAllMocks();
  jest.spyOn(Date, 'now').mockRestore();
});
LazioTibijczyk
  • 1,701
  • 21
  • 48

2 Answers2

0

I have solved a similar issue by calling mockRestore of the returned value of the jest.spyOn(), that also returns a Jest mock function. Oficcial docs.

Norayr Ghukasyan
  • 1,298
  • 1
  • 14
  • 28
  • This answer did not work for me. I tried: `let spy = jest.spyOn(testFeature.Service, 'getObj').mockImplementation(() => {return 'junk';});` `spy.mockRestore();` It was not restored in later tests. – OpticalFlow Feb 01 '23 at 18:29
0

I think you should use jest.restoreAllMocks(). As the docs says

since Jest 21.1.0 Restores all mocks back to their original value. Beware that jest.restoreAllMocks() only works when mock was created with jest.spyOn;

So your code should be like :

 beforeEach(() => {    
    jest.restoreAllMocks();
 });
ninoorta
  • 662
  • 1
  • 5
  • 13