在反应测试库中通过标签查询material-ui输入

Query for material-ui input by label in react testing library

我正在尝试编写一个测试用例来断言在选择单选选项时数字输入被禁用并且在使用 React 测试库实用程序查询 HTML <input> 时遇到问题由 Material UI <TextField>.

渲染

此测试适用的组件中有两个 <TextField> 实例,因此我尝试使用 findAllByLabelText 查询,然后循环遍历这些节点以确认禁用状态。

React 组件

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();
  });
});

预期结果

我希望输入节点能被标签文本找到,并被禁用,从而通过测试。

实际结果

我在测试输出中收到以下错误消息:

Found a label with the text of: Custom Pricing, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly.

好吧,显然我所要做的就是将堆栈溢出用作橡皮鸭,因为我立即想通了..

解决方案

只需将 id 属性添加到 <TextField>

MUI TextField 中的 labelinput 未正确链接到 for 属性,除非您提供 id 道具,如前所述在 MUI TextField docs.

Accessibility 部分下

也许单元测试终究会迫使我采用最佳实践..