【问题标题】:Query for material-ui input by label in react testing libraryreact测试库中按标签查询material-ui输入
【发布时间】: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


    【解决方案1】:

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

    解决方案

    只需将id 属性添加到&lt;TextField&gt;

    MUI TextField 中的 labelinput 没有与 for 属性正确链接,除非您提供 id 属性,如 Accessibility 部分所述MUI TextField docs

    也许单元测试毕竟会迫使我使用最佳实践......?

    【讨论】:

    • 知道如何在重复使用的组件中进行这项工作吗?我试过使用 inputRef 但无济于事......
    猜你喜欢
    • 2021-10-27
    • 2021-02-12
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多