While testing Jest, I encountered the following issue with the manual mock file of isomorphic-fetch
:
// __mocks__/isomorphic-fetch.ts
import * as req from "./requestData";
const Fetch = (url: string, options: any): Promise<any> => {
const resultPromise = {
text: () => {
return Promise.resolve(req.generateMockResponseData(url, options.body));
},
};
return Promise.resolve(resultPromise);
};
export default Fetch;
Despite returning the expected values, when attempting to analyze the arguments passed to it, I found that the mock
property on fetch
was undefined. I tried two different approaches to resolve this issue:
Firstly, I wrapped the Fetch
function in a jest.fn
like so:
const Fetch = jest.fn((url: string, options: any): Promise<any> => {
// implementation remains the same
});
export default Fetch;
After adding
import _fetchMock from "isomorphic-fetch"
const fetchMock = _fetchMock as jest.Mock<Promise<any>>;
to the test file, I was able to inspect fetch calls using
fetchMock.mock.calls[0]
However, now during tests, fetch
in the application code started returning undefined for some reason.
Secondly, I removed the jest.fn
wrapper from Fetch
and included
jest.mock("isomorphic-fetch")
in the test file. This led to fetch
returning the expected values during tests in the application code, but fetchMock.mock
became undefined again.
For Jest configuration, refer to the snippet below:
// jest.config.js
module.exports = {
"clearMocks": true,
"coverageDirectory": "../coverage",
"resetMocks": true,
"restoreMocks": true,
"rootDir": "./src",
"testEnvironment": "jsdom",
"preset": "ts-jest",
"coveragePathIgnorePatterns": ["Error.ts"],
"testEnvironmentOptions": {
"resources": "usable",
"features": {
"FetchExternalResources": ["script", "iframe"],
"ProcessExternalResources": ["script", "iframe"],
}
}
}
For a detailed example, please visit GitHub.