React Jest snapshots using enzyme-to-json example

Install enzyme-to-json package

yarn add enzyme-to-json

create A stateless component

import React from ‘react’;

const About = () => {
return (
<div id=”about”>
<h2>Heading one</h2>
<h4>Lorem ipsum dolor sit amit</h4>
<h2>Heading two</h2>
<h4>Lorem ipsum dolor sit amit</h4>
<h2>Heading three</h2>
<h4>Lorem ipsum dolor sit amit</h4>
</div>
);
}

export default About;

let’s test this component.

create a test file About.test.js  and add the following code.

import React from ‘react’;
import { shallow } from ‘enzyme’;
import { shallowToJson } from ‘enzyme-to-json’;

//import about component
import About from ‘../components/auth/About’;

describe(‘About component’, () => {
const wrapper = shallow(<About />);

it(‘renders properly’, () => {
expect(shallowToJson(wrapper)).toMatchSnapshot();
});

it(‘it has a div’, () => {
expect(wrapper.find(‘div’).length).toBe(1);
});

it(‘it has h2 and h4 headers’, () => {
expect(wrapper.find(‘h2’).length).toBe(3);
expect(wrapper.find(‘h4’).length).toBe(3);
});

});

save it and run yarn test

It’ll create a file About.test.js.snap file

Always update your snapshots while testing using press U

Leave a Reply

Your email address will not be published. Required fields are marked *