4

I am currently using Material UI and react-testing-library on a form. I have a Select which is populated by an array of objects.

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;

In my testing file what I want to be able to do is check if the actual value of the select is correct. I can always just check the label but in this scenario the value is what is import. So if I select Example 1. I want to run a test to check to see if the selectedOption input has a value of 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
  });
});

I have seen some questions where people say use the data-testId prop but I don't really want to use that since it's the last thing react-testing-library recommends to use.

I also don't want to use Enzyme as it isn't supported with React 18 anymore

Richard Hpa
  • 2,353
  • 14
  • 23
  • Does this answer your question? [React testing library on change for Material UI Select component](https://stackoverflow.com/questions/55184037/react-testing-library-on-change-for-material-ui-select-component) – juliomalves Jul 18 '21 at 14:58
  • 3
    Not really because I said I dont want to use testId but that example does – Richard Hpa Jul 18 '21 at 20:45

1 Answers1

-2

Using 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");
Chogainz
  • 17
  • 1
  • 2