Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Testing Library: Match Number of Buttons

I have created an app using create-react-app. Below is my counter component and testing file. I am trying to create a test for the three static buttons I have in my component. The first test runs fine while the 2nd test gives the error provided below.

REACT COMPONENT:

    import React from "react";
    import PropTypes from "prop-types";
    import classes from "./Counter.module.css";
    function Counter(props) {
      return (
        <div className={classes.Wrapper}>
          <div>
            <p>
              Click Counter -  {props.value}
            </p>
          </div>
          <div>
            <button onClick={props.counterIncrement} className={classes.custButton} name="first"> Increment </button>
            {/* <button onClick={props.counterDecrement} className={classes.custButton}> Decrement </button>
            <button onClick={props.resetCounter} className={classes.custButton}> Reset </button> */}
          </div>
        </div>
      );
    }
    Counter.propTypes = {
      value: PropTypes.number,
      clickHandler: PropTypes.func,
    };
    export default Counter;

TESTING FILE:

    import React from 'react'
    import {render, fireEvent, screen, cleanup} from '@testing-library/react'
    
    import Counter from "./Counter";
    
    
    afterEach(cleanup);
    
    describe('Counter', () => {
        test('renders counter value 10', () => {
          render(<Counter />);
          //screen.debug();
          expect(screen.getByText(/Click Counter -/)).toBeInTheDocument();
        })
    
    })
    
    test('renders three buttons', () => {
        render(<Counter />);
        const items = screen.findAllByRole('button');
        expect(items).toHaveLength(3);
      })

ERROR MESSAGE:

FAIL src/components/Counter/Counter.test.js ● renders three buttons expect(received).toHaveLength(expected) Matcher error: received value must have a length property whose value must be a number Received has type: object Received has value: {} 19 | render(); 20 | const items = screen.findAllByRole('button'); > 21 | expect(items).toHaveLength(3); | ^ 22 | }) at Object..test (src/components/Counter/Counter.test.js:21:19)*

like image 877
Ashish Avatar asked Aug 15 '20 15:08

Ashish


1 Answers

In your provided example, you are using .findAllByRole('button'), which returns a promise and needs to be awaited like so:

test('renders three buttons', async () => {
  render(<Counter />)
  const items = await screen.findAllByRole('button')
  expect(items).toHaveLength(3)
})

The other solution would be to use .getAllByRole('button'), in which case you can assert on the result immediately.

like image 88
Dobby Dimov Avatar answered Nov 15 '22 08:11

Dobby Dimov