...

/

Test Styled Components

Test Styled Components

Learn how to test the styled-components using Jest.

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 CarouselSlide only has the props it receives from Carousel. That assumption no longer holds now that CarouselSlide has 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;
     
...