【发布时间】:2021-06-23 08:00:58
【问题描述】:
我正在尝试编写一个测试用例来断言在选择单选选项时禁用数字输入,并且在使用 React 测试库实用程序查询由 Material UI <TextField> 呈现的 HTML <input> 时遇到问题.
此测试适用的组件中有两个<TextField> 实例,因此我尝试使用findAllByLabelText 查询,然后遍历这些节点以确认禁用状态。
反应组件
function OverridePriceModal () {
...
return (
<>
...
<TextField
type="number"
label="Custom Pricing"
value={regularPriceOverride}
onChange={evt => setRegularPriceOverride(evt.target.value)}
disabled={!isRegularPriceOverridden}
/>
...
<TextField
type="number"
label="Custom Pricing"
value={specialPriceOverride}
onChange={evt => setSpecialPriceOverride(evt.target.value)}
disabled={!isSpecialPriceOverridden}
/>
...
</>
);
}
单元测试
test('custom price inputs are disabled while following system pricing', async () => {
render(<OverridePriceModal />);
const priceInputs = await screen.findAllByLabelText('Custom Pricing');
_.forEach(priceInputs, input => {
expect(input).toBeDisabled();
});
});
预期结果
我希望输入节点可以通过标签文本找到,并被禁用,从而通过测试。
实际结果
我在测试输出中收到以下错误消息:
找到一个带有以下文本的标签:自定义定价,但是没有找到与该标签关联的表单控件。确保您正确使用了“for”属性或“aria-labelledby”属性。
【问题讨论】:
标签: reactjs unit-testing jestjs material-ui react-testing-library