Search code examples
javascripttypescriptunit-testingjestjsmocking

mockResolvedValue is not a function on partial mock with Jest/Typescript


I am trying to partially mock a module, and set the return value for the mocked method as needed in certain tests.

Jest is throwing this error:

mockedEDSM.getSystemValue.mockResolvedValue is not a function
TypeError: mockedEDSM.getSystemValue.mockResolvedValue is not a function

My mock:

jest.mock('../src/models/EDSM', () => ({
  __esModule: true,
  ...jest.requireActual<typeof import('../src/models/EDSM')>('../src/models/EDSM'),
  getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);

Within tests:

it('should test', () => {
  mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});

Typescript is throwing no warnings in the IDE, I'm only getting errors from Jest when running the tests.


Solution

  • Ah of course, found the answer right after posting this!

    No need to call jest.mock at the top of the test file, the only thing needed is to spyOn the method within each test (or in a before/after hook):

    const getSystemValueMock =
      jest.spyOn(EDSM, 'getSystemValue')
      .mockResolvedValue(edsmData);