收到 TypeError: n.getChildContext 不是带有shallowWithIntl的函数

air*_*ine 1 internationalization reactjs jestjs enzyme react-intl

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

\n\n

这是一个测试示例:

\n\n
import React from \'react\';\nimport { loadTranslation, shallowWithIntl } from \'enzyme-react-intl\';\nimport Header from \'../components/Header/Header\';\nloadTranslation("./app/javascript/translations/en-US.json");\n\ndescribe(\'Parent header rendering\', () => {\n     const shallowHeader = shallowWithIntl(<Header />);\n     it(\'matches the snapshot\', () => {\n         expect(shallowHeader).toMatchSnapshot();\n     });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到的测试套件错误。

\n\n

应用程序/javascript/测试失败 /Header.test.jsx\n \xe2\x97\x8f 父标头渲染 \xe2\x80\xba 遇到声明异常

\n\n
TypeError: n.getChildContext is not a function\n\n   5 | \n   6 | describe(\'Parent header rendering\', () => {\n>  7 |     const shallowHeader = shallowWithIntl(<Header />);\n     |                           ^\n   8 |     it(\'matches the snapshot\', () => {\n   9 |         expect(shallowHeader).toMatchSnapshot();\n  10 |     });\n\n  at _enzyme (node_modules/enzyme-react-intl/lib/webpack:/enzyme-react-intl/src/index.js:47:12)\n  at Suite.<anonymous> (app/javascript/__tests__/Header.test.jsx:7:27)\n  at Object.describe (app/javascript/__tests__/Header.test.jsx:6:1)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我是一个反应/笑话/酶菜鸟,就其现状而言,我想学习,所以任何指点和批评都将受到极大的赞赏,无论它们对我的灵魂有多大的影响。

\n\n

提前致谢!

\n

air*_*ine 5

不要使用目前已与 getChildContext 方法一起弃用的ase-react-intl 包,而是参考react-intl 自述文件中最新的辅助函数;酶测试链接。代码是用 typescript 编写的,要更改为 js/jsx 只需要进行少量编辑。代码如下。希望这可以帮助。不要忘记评论react-intl 存储库中的来源。

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,
     },
  });
}
Run Code Online (Sandbox Code Playgroud)