用于材料 ui 文本输入的 react-testing-library

Ruc*_*mar 7 react-testing-library

我的文本输入是

<TextField
      className={classes.textField}
      data-testid={name}
      variant="outlined"
      error={false}
      required
      onChange={element => {
        if (onTextChange) {
          onTextChange(name, element.target.value);
        }
      }}
      disabled={!editEnable}
      name={name}
      label={label}
      defaultValue={values}
      fullWidth
    />
Run Code Online (Sandbox Code Playgroud)

和 UI 在此处输入图像描述

如何在反应测试库中更改此文本元素的值?

Iva*_* K. 21

就我而言,它是这样工作的

it('should render input ', () => {
    const field  = screen.getByTestId('search-text-field').querySelector('input')
    expect(field ).toBeInTheDocument()

    fireEvent.change(field , {target: { value: 'some text'}});
    expect(field.value).toBe('some text');
});
Run Code Online (Sandbox Code Playgroud)

  • 根据 MUI 文档 https://mui.com/material-ui/guides/testing/,通过 `input` 或 `role="textbox"` 查询被认为比通过 MUI 实例的 testid 查询更好 (2认同)

Ric*_*Hpa 11

我不认为通过显示值获取输入是一个好主意,因为如果改变整个测试就会失败。相反,您应该获取输入字段的标签。

screen.getByLabelText(/^label/i)
Run Code Online (Sandbox Code Playgroud)

更新

刚刚意识到,只有在 TextField 中包含 id 并且该 ID 必须与名称匹配时,我的方法才有效。这似乎确实是通过 Material UI 获取输入的首选方式,因为您不需要包含测试 ID 或值。

screen.getByLabelText(/^label/i)
Run Code Online (Sandbox Code Playgroud)


Tho*_*Kay 9

我经常很难让 Material UI 和反应测试库正常工作。但如果你知道你的“食谱”,它总是一样的。

这是一个文本字段的示例

import * as React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { TextField } from '@material-ui/core';

const inputMock = jest.fn();

const Test = () => (
  <TextField
    data-testid={name}
    variant="outlined"
    error={false}
    required
    onChange={inputMock}
    name={name}
    label={'label'}
    defaultValue={'4711'}
    placeholder={'Enter Number'}
    fullWidth
  />
);

test('Input', () => {
  const container = render(<Test />);

  const input = container.getByDisplayValue('4711') as HTMLInputElement;

  fireEvent.change(input, { target: { value: '42' } });
  expect(input.value).toBe('42');
  expect(inputMock.mock.calls).toHaveLength(1);
});
Run Code Online (Sandbox Code Playgroud)

以下是使用哪些选择器的一些建议。所以你可以尝试一种“更好”的。 https://testing-library.com/docs/guide-which-query

干杯托马斯