Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 288
Danny Avatar asked Mar 29 '26 19:03

Danny


2 Answers

Iterate the buttons array and run the expect for each one

buttons.forEach((button) => {
   expect(button).toHaveAttribute('disabled');
})
like image 179
diedu Avatar answered Apr 01 '26 09:04

diedu


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
like image 28
Deotyma Avatar answered Apr 01 '26 08:04

Deotyma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!