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.
Mock Implementations Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with jest.fn or the mockImplementationOnce method on mock functions. const myMockFn = jest.fn(cb => cb(null, true));
When testing JavaScript code using Jest, sometimes you may find yourself needing to mock a module. Whether it’s because the module or the functions it exports are irrelevant to the specific test, or because you need to stop something like an API request from trying to access an external resource, mocking is incredibly useful.
Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the jest.mock (...) function to automatically mock the axios module. Once we mock the module we can provide a mockResolvedValue for .get that returns the data we want our test to assert against.
The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called. jest.fn (implementation) is a shorthand for jest.fn ().mockImplementation (implementation). .mockImplementation () can also be used to mock class constructors:
Thanks, Andrew Haines, the comments on the related issue you posted provides a solution. I am satisfied with the following:
const mock = (mockFn: any) => mockFn;
test("something when funcOne returns 'foo'", () => {
mock(funcOne).mockImplementation(() => 'foo'); // mo more flow errors!
...
});
You can loosen the type constraint inline as well:
test("something when funcOne returns 'foo'", () => {
(funcOne: any).mockImplementation(() => 'foo'); // mo more flow errors!
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With