【问题标题】:Testing library React - expect multiple elements to pass a specified condition测试库 React - 期望多个元素通过指定条件
【发布时间】:2021-10-26 10:20:38
【问题描述】:
我的组件中有多个按钮,所有这些按钮都应该被禁用。
const buttons = screen.getAllByRole('button');
expect(ALL BUTTONS).toHaveAttribute('disabled'); // I want something like this.
我们怎样才能用最方便的方式写这个?
【问题讨论】:
标签:
reactjs
jestjs
react-testing-library
testing-library
【解决方案1】:
迭代按钮数组并为每个按钮运行期望
buttons.forEach((button) => {
expect(button).toHaveAttribute('disabled');
})
【解决方案2】:
我在测试中使用了这段代码:
buttons.forEach((button) =>{
expect(button).toBeDisabled()
})
或者你可以这样写:
expect(buttons).toBeDisabled().toHaveLength(2)//here you put number of your buttons