cel*_*ade 21 unit-testing reactjs react-test-renderer
我开始学习React,当我做一些测试时,我注意到两条警告信息:
警告:ReactTestUtils已移至react-dom/test-utils.更新引用以删除此警告.
警告:浅层渲染器已移至react-test-renderer/shallow.更新引用以删除此警告.
它们不会阻止测试运行也不会阻止正确验证,但始终存在此错误.
通过查看文档,我找到了这个页面,即使在我列出他们推荐的那些行之后,警告信息仍然显示出来.
我正在尝试一个非常简单的测试,这是我的代码:
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);
})
})
Run Code Online (Sandbox Code Playgroud)
为解决此警告,我需要做什么?我已将所有打包更新到最新版本.
Per*_*ges 22
如果您使用React 0.14或React <15.5,除了酶之外,您还必须确保安装了以下npm模块(如果它们尚未安装):
npm i --save-dev react-addons-test-utils react-dom
Run Code Online (Sandbox Code Playgroud)
如果您使用React> = 15.5,除了酶之外,您还必须确保安装了以下npm模块(如果它们尚未安装):
npm i --save-dev react-test-renderer react-dom
Run Code Online (Sandbox Code Playgroud)
Mic*_*per 16
我认为它来自于使用shallow来自酶的render函数,它尚未针对v15.5进行更新(尽管有拉取请求).
您可以尝试使用其他渲染函数(render或mount)之一,但这将更改测试的语义(并且可能会或可能不会产生警告).
您的另一个选择是不使用酶并react-test-renderer/shallow自己使用,但酶API非常适合测试组件.
我的建议是等待酶的版本,并暂时接受警告.