reactjs - 点击【React】后测试组件中的每个按钮是否被禁用
问题描述
我有一个组件,它映射一些方向并<button>
为每个方向呈现一个。单击按钮时,它被禁用。
我必须设置一个测试来确定单击后按钮是否被禁用。
我的组件:
<div>
{sortDirections.map((sortDirection) => (
<button
key={sortDirection}
disabled={
sortFilters.direction === sortDirection &&
sortFilters.payType === sortVariant.payType
}
className="btn"
onClick={() =>
handleSortFilters({
payType: sortVariant.payType,
direction: sortDirection,
})
}
>
{sortDirection}
</button>
))}
</div>
到目前为止,我将提供我的测试,但它确实有错误
it('Sort button should be disabled on click', () => {
render(
<ProductSorter
sortFilters={sortFilters}
handleSortFilters={handleSortFilters}
/>
);
expect(screen.getAllByRole('button')).toHaveLength(4);
// ERROR: Argument of type 'HTMLElement[]' is not assignable to parameter of type 'Element | Node | Document | Window'.
fireEvent.click(screen.getAllByRole('button'));
});
我可以成功测试一个按钮,但由于它是一组按钮而苦苦挣扎,我需要测试每个按钮。想知道我是否必须单独编写带有特定测试的每个按钮?
解决方案
您应该能够在数组上使用 forEach 循环:
it('Sort button should be disabled on click', () => {
render(
<ProductSorter
sortFilters={sortFilters}
handleSortFilters={handleSortFilters}
/>
);
const buttons = screen.getAllByRole('button')
buttons.forEach((x)=>expect(x).toHaveProperty('disabled'))
});
推荐阅读
- javascript - 数组的Vue单击事件
- node.js - 具有多个指定相同运算符的表达式的 mongo 查询
- julia - 具有与字段值相同数量的参数的外部构造函数
- intellij-idea - Rust 编译模式之间的区别
- javascript - 从 Ajax 成功加载所有数据后,我想使用另一个 ajax 来更改图像 loading.gif
- ios - Swift :- 线程 1:致命错误:余数或除以零
- twitter-bootstrap - Bootstrap 4 导航栏,带有品牌中心和左侧、中心和右侧的链接
- r - plotly R条形图更新直接标签数据
- orchardcms - ContentPartRecord 和常规 MVC 模型对象有什么区别?
- ios - 关闭应用程序时,Xamarin iOS 保存在领域数据库上