javascript - 在不使用 testid 的情况下测试 Material ui Select 组件

标签 javascript reactjs material-ui react-testing-library

我目前正在表单上使用 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/

相关文章:

javascript - 如何重置 setTimeout

javascript - 为什么我不能将 Angular 变量作为函数参数传递?

javascript - &lt;input&gt; 内的 ref={register} 给了我一个 path.split 错误

javascript - 如何获取 child Prop

reactjs - 将material-ui中的 <TextField/> 组件与react-hook-form一起使用会显示警告

javascript - 使用组件内的选择器将主题/样式应用于所有 html/react 标签

javascript - Application.js 超过 1 Mb Rails

reactjs - 使用 Recoil 创建和读取数千个项目的状态

javascript - 根据动态数据 react 选项卡式内容

reactjs - 如何根据 Material UI 选定的表行设置组件状态