Testing Stateful Components
Learn how to test Stateful Components in this lesson by keeping track of the state and checking event handlers.
We'll cover the following
Introduction to testing stateful components
Both of the React components we’ve built so far are stateless. Their render output is determined entirely by the props they receive, allowing us to express them as a single function. This has the advantage of simplicity. But a carousel is stateful. It needs to keep track of which slide it’s currently showing. In this section, we’ll take a TDD approach to building a Carousel
component with an internal state.
Start with a stub implementation of the component. Since functional components can’t have a state, make it a subclass of React.PureComponent
:
// src/Carousel.js
import React from 'react';
class Carousel extends React.PureComponent {
render() {
return <div />;
}
}
export default Carousel;
Using React.PureComponent
instead of React.Component
tells React that our component doesn’t need to be re-rendered unless its props or state change. It’s a good practice to keep components pure whenever possible, both for performance and for conceptual simplicity.
Add a skeletal test suite:
// src/tests/Carousel.test.js
import React from 'react';
import { shallow } from 'enzyme';
import Carousel from '../Carousel';
describe('Carousel', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Carousel />);
});
it('renders a <div>', () => {
expect(wrapper.type()).toBe('div');
});
});
Now let’s outline some requirements for this component:
-
The carousel keeps track of the current slide with a number,
slideIndex
. -
slideIndex
is initially0
, meaning that the first slide is shown. -
Clicking the “Prev” button decreases
slideIndex
, wrapping around to the index of the last slide when it goes below 0. -
Clicking the “Next” button increases
slideIndex
, wrapping around to0
when it goes above the index of the last slide. -
The carousel takes an array named
slides
and renders the slide indicated byslideIndex
.
Translating these requirements into tests will help us figure out exactly how to implement them.
Testing state
Enzyme’s API for working with state is analogous to its API for working with props.
- Call
wrapper.state(key)
to get the piece of state corresponding to that key:
Get hands-on with 1400+ tech skills courses.