Jest throwing TypeError: Cannot read property 'fetch' of undefined
I am trying to run some tests with Jest in my interactive / reactive library (just inside one business logic).
We are testing actions that use the fetch function (polyfill with whatwg-fetch). I added whatwg-fetch (thanks Safari) for react.
Whenever I try to run a test, I get this error:
TypeError: Cannot read property 'fetch' of undefined
at node_modules/whatwg-fetch/fetch.js:4:11
at Object.<anonymous> (node_modules/whatwg-fetch/fetch.js:461:3)
at Object.<anonymous> (node_modules/jest-expo/src/setup.js:138:416)
What could be causing this problem? Is there a way in the jest config to avoid this?
Here are some files for debugging:
Jest config in package.json
"jest": {
"preset": "jest-expo",
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx"
],
"verbose": true,
"transform": {
"^.+\\.(js|ts|tsx)$": "<rootDir>/node_modules/babel-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"transformIgnorePatterns": [
"node_modules/?!react-native"
]
},
Webpack config:
const config = {
entry: [
'whatwg-fetch',
__dirname + '/src/index.ts',
],
devtool: 'source-map',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.js',
library: 'checkinatwork-module',
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
loaders: [
{ test: /\.(tsx|ts)?$/, loader: 'ts-loader', exclude: /node_modules/ },
],
},
resolve: {
modules: [
'./src',
'node_modules',
],
extensions: ['.js', '.ts', '.jsx', '.tsx', 'json'],
},
plugins: [
],
};
Test file:
import expect from 'expect';
import * as actions from '../../src/components/Checkin/checkin.action';
import * as reducers from '../../src/components/Checkin/checkin.reducer';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
describe('=> ADD CHECKIN ACTIONS', () => {
describe('- REQUEST', () => {
it('Action: ADD_CHECKIN_REQUEST should request addCawCheckin', () => {
const expectedAction = {
type: actions.ADD_CHECKIN_REQUEST,
isFetching: true,
};
expect(actions.addCheckinRequest())
.toEqual(expectedAction);
});
it('Reducer: newCheckin should trigger ADD_CHECKIN_REQUEST and initiate loading', () => {
const expectedState = {
isFetching: true,
status: null,
};
expect(reducers.newCheckin(reducers.newCheckinDefaultState, actions.addCheckinRequest()))
.toEqual(expectedState);
});
});
Action file:
export const getCheckins = (sessionId, date, url, isRefresh) => {
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: {sessionId},
date: {date},
}),
};
return dispatch => {
if (!isRefresh) {
dispatch(getCheckinsRequest());
}
return fetch(url + 'getCAWCheckIns', config)
.then(response => response.json())
.then(({ checkins }) => {
dispatch(getCheckinsSuccess(checkins));
}).catch(err => {
dispatch(getCheckinsError('Get checkins failed'));
console.error('Get checkins failed: ', err);
});
};
};
Thank!
source to share
might be late in the game, but it worked for me.
Possible solution # 1
Note. React.PropTypes has been deprecated since React v15.5. Use the prop-types library instead.
If you install the npm package prop types, it has isomorphic-fetch
as a dependency. This will give you the sample as global. You will still have to import it into a test file. You may need to exclude it from your linter as well.
add this to the beginning of your test file.
import fetch from 'isomorphic-fetch'
I didn't need to call fetch on the test suite, but I needed to make it available.
If you use this approach I think you would remove 'whatwg-fetch',
from your entry in the web folder
Hope it helps
Updated: Possible Solution # 2
Using @zvona's example above but create a MOCKS folder in your application . then the file /globalMock.js. You may not have configured it correctly.
__MOCKS__/globalMock.js
// use one of these imports
import { fetch } from 'whatwg-fetch' // if you want to keep using the polyfill
import { fetch } from 'isomorphic-fetch' // from a dependency node module that I spoke of in the previous solution.
global.fetch = fetch
Now in package.json
add this to your Jest config:
"jest": {
"verbose": true,
"rootDir": "app",
"setupFiles": ["<rootDir>/__MOCKS__/globalMock.js"]
}
this will allow you to use sampling in your tests.
I also had to use this same concept for localStorage. Where I keep all my globals that Jest has no access to.
source to share
This worked for me. In your export customize the file (node_modules / jest-expo / src / setup.js) where it requires whatwg-fetch, I changed which requires require ('fetch-everywhere')
const { Response, Request, Headers, fetch } =
require('fetch-everywhere');
global.Response = Response;
global.Request = Request;
global.Headers = Headers;
global.fetch = fetch;
For some reason, only in all cases worked with expo and jest.
source to share