ReactTestUtils 已被移动

ReactTestUtils has been moved

我开始学习 React,在做一些测试时,我注意到两条警告消息:

Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.

Warning: Shallow renderer has been moved to react-test-renderer/shallow. Update references to remove this warning.

它们不会阻止测试 运行 也不会阻止正确验证,但总是会出现此错误。

通过查看文档,我 found this page,即使在我包含了他们推荐的那些行之后,警告消息仍然出现。

我正在尝试一个非常简单的测试,这是我的代码:

import React from "react";
import toJson from "enzyme-to-json";
import { shallow } from "enzyme";
import { About } from "./About";

describe('Rendering test', () => {
    const component = shallow(<About />);
    const tree      = toJson(component);

    it('Should render the About component', () => {
        expect(tree).toMatchSnapshot();
    })

    it('Should not contain an h2 element', () => {
        expect( component.contains('h2') ).toBe(false);
    })
})

我需要做什么才能解决这个警告?我已经将我所有的打包更新到最新版本。

我认为它来自于使用酶的 shallow 渲染功能,它还没有为 v15.5 更新(虽然有一个 pull request)。

您可以尝试使用其他渲染函数之一 (render or mount),但这会改变测试的语义(并且可能会或可能不会仍然产生警告)。

您的另一个选择是不使用酶而使用 react-test-renderer/shallow yourself,但是酶 API 非常适合测试组件。

我的建议是等待酶的版本,暂时接受警告。

如果您使用的是 React 0.14 或 React <15.5,除了酶之外,您还必须确保安装了以下 npm 模块(如果尚未安装):

npm i --save-dev react-addons-test-utils react-dom

如果您使用的是 React >=15.5,除了 enzyme 之外,您必须确保还安装了以下 npm 模块(如果尚未安装):

npm i --save-dev react-test-renderer react-dom

2017 年 8 月更新

如果你安装 react-test-renderer 它会工作,但所有 react-* 版本应该匹配:

例如
react@15.4.2
react-test-renderer@15.4.2
react-dom@15.4.2
react-addons-test-utils@15.4.2

在我的环境中,只有这个配置有效!

在尝试上述步骤后,我仍然收到以下警告。

警告:ReactTestUtils 已移至 react-dom/test-utils。更新引用以删除此警告。

更新 \node_modules\react-addons-test-utils\index.js 中的路径为我解决了这个问题。

旧:

lowPriorityWarning(
  false,
  'ReactTestUtils has been moved to react-dom/test-utils. ' +
    'Update references to remove this warning.'
);

module.exports = require('react-dom/lib/ReactTestUtils');

新:

lowPriorityWarning(
  false,
  'ReactTestUtils has been moved to react-dom/test-utils. ' +
    'Update references to remove this warning.'
);

module.exports = require('react-dom/test-utils');