Receiving TypeError: n.getChildContext is not a function with shallowWithIntl

Receiving TypeError: n.getChildContext is not a function with shallowWithIntl

几周前,我与同事一起开始了一个项目,该项目使用 React 前端和 ruby 后端。经过几次代码审查后,关于有一个未国际化的应用程序的评论又回到了我们身边。我们有一个使用 i18n gem 的国际化后端,但被告知反应的标准是使用 react-intl 作为前端国际化包。 我刚刚完成了国际化的编码,用几种语言对其进行了测试以确保其正常工作。关于测试主题,我开始 运行 解决一个我一直在用头撞墙的问题。 我一直收到此错误:n.getChildContext不是函数。 我正在使用包 enzyme-react-intl。为了测试这是否有效,我决定只从拍摄我的组件(功能性和基于 class 的组件)的快照开始。下面是我的一个测试示例以及我收到的测试套件失败。我所有带有 shallowWithIntlmountWithIntl 的测试套件都失败了。我应该注意,我是 运行 我使用命令进行的测试:'yarn jest -u'。从我阅读的所有搜索和 api 文档中,我没有犯任何 明显的 错误,但希望能提供任何帮助。

这里是一个例子测试:

import React from 'react';
import { loadTranslation, shallowWithIntl } from 'enzyme-react-intl';
import Header from '../components/Header/Header';
loadTranslation("./app/javascript/translations/en-US.json");

describe('Parent header rendering', () => {
     const shallowHeader = shallowWithIntl(<Header />);
     it('matches the snapshot', () => {
         expect(shallowHeader).toMatchSnapshot();
     });
});

我收到测试套件错误。

失败app/javascript/测试/Header.test.jsx ● 父头渲染 › 遇到声明异常

TypeError: n.getChildContext is not a function

   5 | 
   6 | describe('Parent header rendering', () => {
>  7 |     const shallowHeader = shallowWithIntl(<Header />);
     |                           ^
   8 |     it('matches the snapshot', () => {
   9 |         expect(shallowHeader).toMatchSnapshot();
  10 |     });

  at _enzyme (node_modules/enzyme-react-intl/lib/webpack:/enzyme-react-intl/src/index.js:47:12)
  at Suite.<anonymous> (app/javascript/__tests__/Header.test.jsx:7:27)
  at Object.describe (app/javascript/__tests__/Header.test.jsx:6:1)

就目前而言,我有点 react/jest/enzyme 菜鸟,我想学习,所以任何指点和批评都非常感谢,无论他们吃多少我的灵魂。

提前致谢!

与其使用目前已被 getChildContext 方法弃用的 enzyme-react-intl 包,不如参考 react-intl 自述文件中最新的辅助函数; link to testing with enzyme。代码是用打字稿写的,要更改为 js/jsx 只需要一个小的编辑。代码如下。希望这可以帮助。不要忘记评论来自 react-intl repo 的来源。

import React from 'react';
import {IntlProvider} from 'react-intl';
import {mount, shallow} from 'enzyme';

// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('./translations/en-US.json'); // en-US.json
const defaultLocale = 'en-US';
const locale = defaultLocale;

export function mountWithIntl(node) {
  return mount(node, {
    wrappingComponent: IntlProvider,
    wrappingComponentProps: {
      locale,
      defaultLocale,
      messages,
   },
  });
}

  export function shallowWithIntl(node) {
   return shallow(node, {
     wrappingComponent: IntlProvider,
     wrappingComponentProps: {
      locale,
      defaultLocale,
      messages,
     },
  });
}