How to see what the rendered React component looks

2020-05-06 17:14发布

问题:

I'm trying to run a test for the React component. I need to check how it looks like after rendering. Tried to use ReactDOMServer.renderToString() but it fails. 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); then I get this error:

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

Does anyone knows where the problem is?

回答1:

There is the snapshot feature in Jest where it stores the rendered tree as a file. Note that you have to install enzyme-to-json as well to convert the enzyme rendered component to something the snapshot method can understand.

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. Every time you rerun the test, the component will be tested against the snapshot.



回答2:

If you don't use enzyme, you can use Facebook's react-test-renderer too, it's even simpler:

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