Testing library React - expect multiple elements to pass a specified condition
Asked Answered
M

2

11

I have multiple buttons in my component and all of them should be disabled.

const buttons = screen.getAllByRole('button');

expect(ALL BUTTONS).toHaveAttribute('disabled'); // I want something like this.

How can we write this in the most convenient way?

Markson answered 23/10, 2021 at 3:26 Comment(0)
H
12

Iterate the buttons array and run the expect for each one

buttons.forEach((button) => {
   expect(button).toHaveAttribute('disabled');
})
Hoop answered 23/10, 2021 at 3:30 Comment(0)
H
2

I used this code in my test:

buttons.forEach((button) =>{
    expect(button).toBeDisabled()
})

or you can write this:

 expect(buttons).toBeDisabled().toHaveLength(2)//here you put number of your buttons
Hawes answered 25/10, 2021 at 18:1 Comment(1)
The second one is a short and convenient way as well, thank you, sir!Markson

© 2022 - 2024 — McMap. All rights reserved.