reactjs - 开 Jest 抛出 TypeError : Cannot read property 'fetch' of undefined

标签 reactjs react-native webpack fetch jestjs

我正在尝试在我的react/react-native库上使用Jest运行一些测试(内部只有一些业务逻辑)。

我们正在测试使用 fetch 函数的操作(polyfill 和 Whatwg-fetch)。 我添加了whatwg-fetch(感谢 Safari)以进行 react 。

每当我尝试运行测试时,都会收到此错误:

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)

什么可能导致此问题? jest 配置中有办法避免这种情况吗?

以下是一些用于调试的文件:

package.json 中的 Jest 配置

"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 配置:

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: [
],
};

测试文件:

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 文件:

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);
      });
  };
};

谢谢!

最佳答案

我已经在规范中完成了它:

import { fetch } from 'whatwg-fetch';

global.fetch = fetch;

它在 Jest 中的表现符合预期。

关于reactjs - 开 Jest 抛出 TypeError : Cannot read property 'fetch' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44045195/

相关文章:

javascript - 在 React 中使用 Lodash debounce 来防止在用户输入时请求数据

reactjs - 如何从 api 迭代对象列表并将其渲染到 jsx 页面 React 功能组件

javascript - 如何将日期和时间组合成一个日期时间对象?

react-native - ReferenceError:找不到变量:文本(我正在使用 expo 应用程序进行 native react )

webpack - Vue CLI - 在静态文件中包含 Assets 文件夹中的图像

android - Cordova Android ReactJS

javascript - 使用 Webpack 进行仅调试页面

React 中的 jQuery UI Datepicker 抛出 Uncaught TypeError

javascript - 在 ES6 中追加对象?

webpack - 如何通过 Webpack 在文件上运行任意 bash 脚本而无需为每种文件类型维护加载程序?