Call Jest mockRestore in TypeScript


Problem

I was trying to invoke mockRestore() on a Jest spy:

jest.spyOn(Date, 'now');
Date.now.mockRestore();

However, TypeScript throws the error:

2339[QF available]: Property 'mockRestore' does not exist on type '() => number'.

Attempt

So I tried doing a type assertion:

(Date.now as jest.SpyInstance).mockRestore();

But that still didn’t work:

2352[QF available]: Conversion of type '() => number' to type 'SpyInstance<{}>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'mockRestore' is missing in type '() => number'.

Solution

Ultimately, I was able to resolve the error by assigning the spy instance to a variable:

const spy = jest.spyOn(Date, 'now');
spy.mockRestore();

This also means the logic can be organized in setup and teardown blocks:

let spy: jest.SpyInstance;

beforeAll(() => {
  spy = jest.spyOn(Date, 'now');
});

afterAll(() => {
  spy.mockRestore();
});


Please support this site and join our Discord!