How to see what the rendered React component looks like in the Jest unit test?

前端 未结 2 1835
盖世英雄少女心
盖世英雄少女心 2021-01-26 14:27

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. Her

2条回答
  •  独厮守ぢ
    2021-01-26 14:52

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

提交回复
热议问题