Test Styled Components
Explore how to test styled-components in React by examining component behavior with Jest and Enzyme. Understand handling default props, shallow versus mount testing, and validating component markup and styles effectively.
We'll cover the following...
We'll cover the following...
Testing styled components using Jest
-
Let’s check how our tests are doing, starting with
Carousel:$ npx jest src/tests/Carousel.test.js FAIL src/tests/Carousel.test.js Carousel ✓ renders a <div> (5ms) ✓ has an initial `slideIndex` of 0 (1ms) ✓ renders a CarouselButton labeled "Prev" (1ms) ✓ renders a CarouselButton labeled "Next" ✕ renders the current slide as a CarouselSlide (12ms) with a middle slide selected ✓ decrements `slideIndex` when Prev is clicked (4ms) ✓ increments `slideIndex` when Next is clicked (1ms) with the first slide selected ✓ wraps `slideIndex` to the max value when Prev is clicked with the last slide selected ✓ wraps `slideIndex` to the min value when Next is clicked (1ms) ● Carousel › renders the current slide as a CarouselSlide expect(received).toEqual(expected) Expected value to equal: {"attribution": "Uno Pizzeria", "description": "Slide 1", "imgUrl": "https://example.com/slide1.png"} Received: {"Img": ...}Currently, the test implicitly assumes that
CarouselSlideonly has the props it receives fromCarousel. That assumption no longer holds now thatCarouselSlidehas default props. -
Let’s update the test to account for those:
// src/tests/Carousel.test.js ... it('renders the current slide as a CarouselSlide', () => { let slideProps; slideProps = wrapper.find(CarouselSlide).props();