Blog post on why and how to use Enzyme
My slides: slides.com/rkotze
Made by Airbnb
Lets see it in action ...
describe('User profile', () => {
let component, dom;
before((done) => {
let person = { FirstName:'Richard', LastName:'Kotze' };
component = ReactDOM.render(
<ProfileBox person={person} />,
document.getElementById('container'),
() => {
setTimeout(done);
}
);
});
after((done) => {
React.unmountComponentAtNode(document.getElementById('container'));
setTimeout(done);
});
it('should contain name', () => {
dom = React.findDOMNode(component);
dom.textContent.should.containEql('Richard Kotze');
});
});
import { mount } from 'enzyme';
describe('User profile', () => {
const person = { FirstName:'Richard', LastName:'Kotze' };
it('should contain name', () => {
const profileDom = mount(<ProfileBox person={person} />);
profileDom.text().should.containEql('Richard Kotze');
});
});
Enzyme provides three ways to render your components.
shallow(<Component />)
Testing the component as a unit and not asserting on child components
Browser environment not needed e.g. jsdom
mount(<Component />)
Full DOM rendering when interacting with DOM API or components that use lifecycle methods.
Browser environment needed e.g. jsdom
render(<Component />)
Render React components to static HTML and analyse the HTML stucture using the Cheerio library.
Browser environment not needed e.g. jsdom
Commonly used methods to help you kick start your React JS testing.
const dom = shallow(<ExampleComponent />);
const exampleList = dom.find('.exampleList li');
exampleList.length.should.equal(3);
If a component contained a list we can use the find method to get the list items and assert the total.
Find() returns a wrapper which will contain an array of elements.
Other selectors to find elements
Component constructor
.find(ExampleComponent);
Component displayName
.find('ExampleComponent');
Object property selector
.find({ magic: 'foo' });
<span magic="foo" />
const dom = shallow(<ExampleComponent />);
const exampleList = dom.find('.exampleList li');
exampleList.get(0).getAttribute('class').should.equal('special');
exampleList.at(1).contains(<li>test</li>).should.be.true();
Get a single element from list
const dom = shallow(<ExampleComponent />);
const exampleList = dom.find('.exampleList li');
dom.debug();
See a string result of rendered mark up.
Useful if your test are failing for an unexpected reason.
Blog post on why and how to use Enzyme
slides.com/rkotze/testing-react-using-enzyme
slides.com/jondarrer/a-simple-node-js-server
By Jonathan Darrer