How to resolve Flow type error from Jest mocking

Viewed 4112

I am using Jest to mock certain functions from a module and to test in the following manner:

jest.mock("module", () => ({
  funcOne: jest.fn(),
  funcTwo: jest.fn(),
  ...
}));

import {funcOne, funcTwo, ...} from "module";

test("something when funcOne returns 'foo'", () => {
  funcOne.mockImplementation(() => 'foo');  // <- Flow error
  expect(...)
});

test("that same thing when funcOne returns 'bar'", () => {
  funcOne.mockImplementation(() => 'bar');  // <- Flow error
  expect(...)
});

How can I stop Flow from reporting a property 'mockImplementation' not found in statics of function error without error suppression (e.g. $FlowFixMe)?

I understand that the issue comes from the fact that the functions defined in the module are not Jest-mocked functions and, as far as Flow is concerned, do not contain methods like mockImplementation, mockReset, etc.

3 Answers

Instead of suppressing the error with any I recommend to use JestMockFn type. Here is a related issue: https://github.com/flow-typed/flow-typed/issues/291

Example (copied from the link above):

import ajax from '../../js/comm/ajax';
jest.mock('../../js/comm/ajax', () => {
  return {
    default: jest.fn(),
  }
});
const mockAjax: JestMockFn<[string], Promise<{body: {}}>> = ajax;
describe('ConfigurationProvider', () => {
  it('calling the fetchConfig() should return a promise', () => {
    const expectedCfg = {x:'y'};
    mockAjax.mockReturnValueOnce(
      Promise.resolve({body:expectedCfg})
    );
    ...
  });
});

Here is how the type is defined in the latest jest version: https://github.com/flow-typed/flow-typed/blob/master/definitions/npm/jest_v25.x.x/flow_v0.104.x-/jest_v25.x.x.js

Note that the type is global and doesn't have to be imported (which is unfortunate decision in my opinion but that is a different topic).

You can loosen the type constraint inline as well:

test("something when funcOne returns 'foo'", () => {
    (funcOne: any).mockImplementation(() => 'foo');  // mo more flow errors!
    ...
});
Related