...

/

Testing Stateful Components

Testing Stateful Components

Learn how to test Stateful Components in this lesson by keeping track of the state and checking event handlers.

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 ...

Access this course and 1400+ top-rated courses and projects.