Manipulating State of Stateful Component in Tests
Let’s learn how to manipulate states of a stateful component through Enzyme's method in tests.
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 theslides
prop on theCarousel
instance, then add a (failing) test for the slide-passing behavior:
Press + to interact
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(); // 1expect(slideProps).toEqual(slides[0]); // 2wrapper.setState({ slideIndex: 1 }); // 3slideProps = wrapper.find(CarouselSlide).props();expect(slideProps).toEqual(slides[1]);});});
...
- The
Access this course and 1400+ top-rated courses and projects.