Piero Divasto
Full-stack developer
M.Sc. in Business Informatics
Team Lead & Full-stack Developer @ Nisum
Lead de Facebook Developers Circle: Santiago
https://stateofjs.com/2017/testing/results
expect
Concepts
shallow
mount
render
used to render react components to static HTML and analyze the resulting HTML structure.
Full DOM rendering is ideal for use cases where you have components that may interact with DOM APIs, or may require the full lifecycle in order to fully test the component (i.e., componentDidMount etc.)
Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.foo')).to.have.lengthOf(1);
expect(wrapper.find('.bar')).to.have.lengthOf(3);
// compound selector
expect(wrapper.find('div.some-class')).to.have.lengthOf(3);
// CSS id selector
expect(wrapper.find('#foo')).to.have.lengthOf(1);
// Constructor selector
import Foo from '../components/Foo';
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1);
// Component display name
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);
// Object property selector
const wrapper = shallow(<MyComponent />);
expect(wrapper.find({ prop: 'value' })).to.have.lengthOf(1);
Snapshot testing
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer
.create(<Link page="http://www.facebook.com">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
exports[`renders correctly 1`] = `
<a
className="normal"
href="http://www.facebook.com"
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
Facebook
</a>
`;
Snapshot testing
By Piero Divasto