测试点击【React】后组件中的各个按钮是否被禁用
Test if each button in a component is disabled after click [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'));
});
我可以成功测试一个按钮,但由于它是一组按钮,所以我很费劲,我需要测试每个按钮。想知道我是否必须单独为每个按钮编写特定测试?
因为screen.getAllByRole('button')
return一个元素数组。所以你可以像这样使用一个循环来点击每个元素:
screen.getAllByRole('button').forEach(element => {
fireEvent.click(element )
})
您应该可以在数组上使用 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'))
});
我有一个组件,它映射某些方向并为每个方向呈现一个 <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'));
});
我可以成功测试一个按钮,但由于它是一组按钮,所以我很费劲,我需要测试每个按钮。想知道我是否必须单独为每个按钮编写特定测试?
因为screen.getAllByRole('button')
return一个元素数组。所以你可以像这样使用一个循环来点击每个元素:
screen.getAllByRole('button').forEach(element => {
fireEvent.click(element )
})
您应该可以在数组上使用 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'))
});