【问题标题】:How to see what the rendered React component looks like in the Jest unit test?如何在 Jest 单元测试中查看渲染的 React 组件是什么样的?
【发布时间】:2016-11-09 10:01:15
【问题描述】:

我正在尝试对 React 组件进行测试。我需要检查渲染后的样子。尝试使用ReactDOMServer.renderToString(),但失败了。代码如下:

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 />);
    });
});

我收到以下错误:

Invariant Violation: There is no registered component for the tag component

我试着这样称呼它:var htmlstring = ReactDOMServer.renderToString(component); 然后我得到这个错误:

Invariant Violation: renderToString(): You must pass a valid ReactElement.

有谁知道问题出在哪里?

【问题讨论】:

    标签: javascript unit-testing reactjs jestjs


    【解决方案1】:

    在 Jest 中有 snapshot feature,它将渲染的树存储为文件。请注意,您还必须安装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();
      });
    });
    

    这将在您的测试文件夹中的__snapshot__ 文件夹中创建一个新文件,您可以在其中检查渲染结果。每次重新运行测试时,都会针对快照对组件进行测试。

    【讨论】:

      【解决方案2】:

      如果不用酵素,也可以用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();
      });
      

      【讨论】:

        猜你喜欢
        • 2018-04-03
        • 2018-05-29
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 2021-09-01
        • 1970-01-01
        相关资源
        最近更新 更多