我目前正在表单上使用 Material UI 和 react-testing-library。我有一个由对象数组填充的 Select。
import React, { useState } from 'react';
import { Select, MenuItem, FormControl, InputLabel } from '@material-ui/core';
const options = [
{
label: 'Example 1',
value: 123456789,
},
{
label: 'Example 2',
value: 987654321,
},
];
const SelectTesting = () => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<FormControl variant="outlined" fullWidth>
<InputLabel id="selectedOptionLabel">Select an Option</InputLabel>
<Select
labelId="selectedOptionLabel"
id="selectedOption"
value={value}
onChange={handleChange}
label="Select an Option"
>
{options.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</Select>
</FormControl>
);
};
export default SelectTesting;
在我的测试文件中,我想要做的是检查选择的实际值是否正确。我总是可以只检查标签,但在这种情况下,值就是导入的值。因此,如果我选择示例 1。我想运行一个测试来检查 selectedOption 输入的值是否为 123456789
import React from 'react';
import { screen, render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SelectTesting from '.';
describe('SelectComponent', () => {
it('value should be 123456789', async () => {
render(<SelectTesting />);
const select = await screen.findByLabelText(/^select an option/i);
userEvent.click(select);
const option = await screen.findByRole('option', { name: /^example 1/i });
userEvent.click(option);
// want to check to see if value is 123456789
});
});
我看到一些问题,人们说使用 data-testId Prop ,但我真的不想使用它,因为它是 react-testing-library 建议使用的最后一件事。
最佳答案
使用 Enzyme、Jest 和 Material UI V4/V5
const wrapper = mount(<SelectTesting />);
const select = wrapper.find({ id: [select_id], role: "button" }).hostNodes();
select.simulate("mouseDown", { button: 0 });
const option = wrapper.find({id: [option_id] }).hostNodes();
option.simulate("click");
关于javascript - 在不使用 testid 的情况下测试 Material ui Select 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68355021/