我的文本输入是:
<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
/>;和UI:

如何在React测试库中更改该文本元素的值?
发布于 2021-10-07 04:21:35
在我的例子中,它是这样工作的
it('should render input ', () => {
const field = screen.getByTestId('search-text-field').querySelector('input')
expect(field ).toBeInTheDocument()
fireEvent.change(field , {target: { value: 'google it'}});
expect(field.value).toBe('google it');
});发布于 2021-06-29 11:57:24
我不认为通过显示值获取输入是一个好主意,因为如果更改了显示值,整个测试就会失败。相反,您应该获得输入字段的标签。
screen.getByLabelText(/^label/i)更新
我刚刚意识到,我的方法只有在TextField中包含一个id,并且ID必须与名称匹配时才有效。这似乎是通过Material UI获取输入的首选方法,因为您不需要包含test-id或通过值。
<TextField
name={name}
id={name}
label={label}
{...otherProps}
/>发布于 2020-09-02 04:44:26
我经常努力让Material UI和react-testing-library工作。但是如果你知道你的“食谱”,它总是一样的。
下面是一个TextField的示例
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);
});下面是一些使用选择器的建议。所以你可以尝试一个“更好”的。https://testing-library.com/docs/guide-which-query
为托马斯干杯
https://stackoverflow.com/questions/63694951
复制相似问题