[英]How to see what the rendered React component looks like in the Jest unit test?
I'm trying to run a test for the React component. 我正在尝试对React组件进行测试。 I need to check how it looks like after rendering. 我需要检查渲染后的外观。 Tried to use ReactDOMServer.renderToString()
but it fails. 尝试使用ReactDOMServer.renderToString()
但失败。 Here is the code: 这是代码:
import { NewRec } from '../src/components/edit';
import { shallow } from 'enzyme';
import React from 'react/lib/ReactWithAddons';
import ReactDOMServer from 'react-dom/server';
jest.mock('react-dom');
jest.mock('react/lib/ReactDefaultInjection');
describe('NewRec component', () => {
const component = shallow(<NewRec />);
it('returns true if blah blah', ()=>{
var htmlstring = ReactDOMServer.renderToString(<component />);
});
});
I'm getting the following error: 我收到以下错误:
Invariant Violation: There is no registered component for the tag component
I tried to call it like: var htmlstring = ReactDOMServer.renderToString(component);
我试图这样称呼它: var htmlstring = ReactDOMServer.renderToString(component);
then I get this error: 然后我得到这个错误:
Invariant Violation: renderToString(): You must pass a valid ReactElement.
Does anyone knows where the problem is? 有谁知道问题出在哪里?
There is the snapshot feature in Jest where it stores the rendered tree as a file. Jest中有快照功能 ,它将快照树存储为文件。 Note that you have to install enzyme-to-json as well to convert the enzyme rendered component to something the snapshot method can understand. 请注意,您还必须安装Enzyme-to-json才能将酶提纯的成分转换为快照方法可以理解的内容。
import { NewRec } from '../src/components/edit';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
describe('NewRec component', () = > {
it('returns true if blah blah', () = > {
const component = shallow(<NewRec />);
expect(shallowToJson(component)).toMatchSnapshot();
});
});
This will create a new file in __snapshot__
folder in your test folder, where you can inspect the rendered result. 这将在测试文件夹的__snapshot__
文件夹中创建一个新文件,您可以在其中检查渲染的结果。 Every time you rerun the test, the component will be tested against the snapshot. 每次您重新运行测试时,都会根据快照对组件进行测试。
If you don't use enzyme, you can use Facebook's react-test-renderer
too, it's even simpler: 如果您不使用酶,那么也可以使用Facebook的react-test-renderer
,它甚至更简单:
import React from "react";
import renderer from "react-test-renderer";
test("Test 1", () => {
const component = renderer.create(
<TestItem />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.