Material-UI 表单和 React 测试库所需的表单字段

Material-UI Form and React Testing Library Required Form Fields

我有一个要测试的 MUI 表单。所有表单字段都是必需的,我想使用 @testing-library/react

进行测试

表格如下:

<form id='xml-form' onSubmit={handleSubmit}>
      <div
        <FormControl required={true}>
          <InputLabel required={true}>Name</InputLabel>
          <Input
            id='firstName'
            data-testid='required-firstName'
            required={true}
          />
        </FormControl>
      </div>
      <div>
        <TextField
          id='lastName'
          data-testid='required-lastName'
          required
          label='Last Name'
          style={{ marginBottom: 15 }}
        />
      </div>
      <Button
        type='submit'
        form='xml-form'
        color='primary'
        variant='contained'
        style={{ marginBottom: 15 }}
      >
        Generate XML
      </Button>
    </form>

下面是我的测试方式:

test('All fields are required', () => {
  render(<XMLForm />);
    expect(
      getByTestId(document.documentElement, 'required-firstName')
    ).toBeRequired();
  expect(
    getByTestId(document.documentElement, 'required-lastName')
  ).toBeRequired();
});

测试在第一个表单域失败。无论我使用 <TextField /> 还是 <FormControl />,呈现的 DOM 元素似乎都没有必填字段,我也不知道为什么。

Received element is not required:
      <div class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-formControl MuiInput-formControl" data-testid="required-firstName" required="" />

       7 |     expect(
       8 |       getByTestId(document.documentElement, 'required-firstName')
    >  9 |     ).toBeRequired();
         |       ^
      10 |   expect(
      11 |     getByTestId(document.documentElement, 'required-lastName')
      12 |   ).toBeRequired();

使用<Input /> or <TextField />时需要将data-testid传递给inputProps:

<form id='xml-form' onSubmit={handleSubmit}>
  <div
    <FormControl required={true}>
      <InputLabel required={true}>Name</InputLabel>
      <Input
        id='firstName'
        inputProps={{ 'data-testid': 'required-firstName' }}
        required={true}
      />
    </FormControl>
  </div>
  <div>
    <TextField
      id='lastName'
      inputProps={{ 'data-testid': 'required-lastName' }}
      required
      label='Last Name'
      style={{ marginBottom: 15 }}
    />
  </div>
  <Button
    type='submit'
    form='xml-form'
    color='primary'
    variant='contained'
    style={{ marginBottom: 15 }}
  >
    Generate XML
  </Button>
</form>

或者,我相信您可以使用 getByLabelText() 查询。对于您感兴趣的两个元素,它将是:

test('All fields are required', () => {
  render(<XMLForm />);
  expect(
    getByLabelText(document.documentElement, 'Name')
  ).toBeRequired();
  expect(
    getByLabelText(document.documentElement, 'Last Name')
  ).toBeRequired();
});