Search⌘ K
AI Features

Manipulating State of Stateful Component in Tests

Explore how to manage and manipulate the state of a stateful React component during testing with Enzyme. Understand how to pass slide data as props, update component state, handle edge cases with click handlers, and declare prop types for clean, testable components. This lesson guides you through writing thorough tests to ensure your Carousel component behaves as expected.

We'll cover the following...

Manipulating state in tests

So far, the carousel is just a pair of buttons. What it really needs is some slides. A simple approach to this is to give the Carousel instance an array of data as a prop called slides, then pass the data from slides[slideIndex] as props to a CarouselSlide.

  • Replace the existing beforeEach block to set the slides prop on the Carousel instance, then add a (failing) test for the slide-passing behavior:
Javascript (babel-node)
import React from 'react';
import { shallow } from 'enzyme';
import Carousel from '../Carousel';
import CarouselButton from '../CarouselButton';
import CarouselSlide from '../CarouselSlide';
describe('Carousel', () => {
let wrapper;
const slides = [
{
imgUrl: 'https://example.com/slide1.png',
description: 'Slide 1',
attribution: 'Uno Pizzeria',
},
{
imgUrl: 'https://example.com/slide2.png',
description: 'Slide 2',
attribution: 'Dos Equis',
},
{
imgUrl: 'https://example.com/slide3.png',
description: 'Slide 3',
attribution: 'Three Amigos',
},
];
beforeEach(() => {
wrapper = shallow(<Carousel slides={slides} />);
});
...
it('renders the current slide as a CarouselSlide', () => {
let slideProps;
slideProps = wrapper.find(CarouselSlide).props(); // 1
expect(slideProps).toEqual(slides[0]); // 2
wrapper.setState({ slideIndex: 1 }); // 3
slideProps = wrapper.find(CarouselSlide).props();
expect(slideProps).toEqual(slides[1]);
});
});
  1. The new test uses a method called props() instead of prop(). This method returns an object containing all of the
...