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