Testing is Tops: Writing Tests for React Apps with Enzyme

Ruth Hill
Ruth Hill
Jan 28, 2018 · 5 min read
Clickable icons should cause a haiku to be rendered
.
├── client
│ └── index.jsx
│ └── components
│ └── Root.jsx
│ └── Header.jsx
│ └── SingleIcon.jsx
│ └── Haikus.jsx
│ └── SingleHaiku.jsx
│ └── store
│ └── index.jsx
│ └── actions.jsx
│ └── reducer.jsx
├── public
│ └── icons
│ └── index.html
│ └── style.css
├── tests
│ └── root.spec.js
│ └── singleicon.spec.js
│ └── haikus.spec.js
│ └── singlehaiku.spec.js
├── app.js
└── server.js
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import Root from '../client/components/Root';describe('<Root />', () => {
const shallowRoot = shallow(Root);
it('should initially render 1 <Header />, 1 <SingleHaiku />, and 8 <SingleIcon /> components', () => {
expect(shallowRoot.find(Header)).to.have.length(1);
expect(shallowRoot.find(SingleHaiku)).to.have.length(1);
expect(shallowRoot.find(SingleIcon)).to.have.length(8);
});
it('has a state containing an object', () => {
const rootState = shallowRoot.state();
expect(rootState).to.be.an('object');
});
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { spy } from 'sinon';
import SingleIcon from '../client/components/SingleIcon';
import Root from '../client/components/Root';
describe('<SingleIcon />', () => {
beforeEach('setHaiku spy', () => {
const mockSetHaiku = spy();
const icon = shallow(<SingleIcon onClick={mockSetHaiku} />)
});
it('calls setHaiku', () => {
icon.simulate('setHaiku', {});
expect(mockSetHaiku.calledOnce).to.be.true;
});
});
// continuing in tests/root.spec.jsimport SingleIcon from '../client/components/SingleIcon';...it('updates state with a new haiku when SingleIcon's click event is handled', () => {    const icon = shallowRoot.find(SingleIcon).nodes.map(shallow);
icon.simulate('setHaiku', {line1: 'Clouds full of moonlight', line2: 'A siren faintly echoes', line3: 'Unit tests abound'});
expect(shallowRoot.state().line1).to.be.equal('Clouds full of moonlight');
expect(shallowRoot.state().line2).to.be.equal('A siren faintly echoes');
expect(shallowRoot.state().line3).to.be.equal('Unit tests abound');
});
// specify your desired spec file path and run it with mocha$ mocha tests/root.spec.js --compilers js:babel-register

Ruth Hill

Written by

Ruth Hill

JavaScript developer, maker, proponent of science, compassion & enthusiasm

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade