简体   繁体   中英

React testing library check amount of disabled elements

I have this component

render(
    <MyComponent data={[{id: 1, disabled: true}, {id: 2, disabled: true}, {id: 3, disabled: false}]} />
);

which renders a list with checkboxes. The ones with disabled true will be disabled in the HTML.

I want to test that the amount of disabled elements is correct (so there should be only 2 disabled).

How can I do this?

This:

screen.getByRole('checkbox'); 

gets me all of them. Or is there any way to check if the last one is disabled?

Could you not get all of your checkboxes with

const checkboxes = screen.getAllByRole('checkbox')

Then fetch the disabled ones

const disabled = checkboxes.filter(c => c.disabled)

Then grab the count

expect(disabled).toHaveLengthOf(2)

If you need the last then maybe

expect(checkboxes[checkboxes.length - 1]).toBeDisabled()

(If you have jest dom )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM