Reputation: 419
I want to test a select change function,here is the code :
import React, { useEffect, useState } from 'react';
import Select from 'react-select';
function Component1(props) {
const [content, setContent] = useState('initialized Value');
const [color, setColor] = useState('initialized Value');
const options = [
{ value: 'red', label: 'Red' },
{ value: 'green', label: 'Green' },
{ value: 'blue', label: 'Blue' },
];
useEffect(async () => {
fetchSomeData();
// onclickButton();
}, []);
const fetchSomeData = async () => {
console.log('fetchSomeData');
};
const onclickButton = () => {
console.log('do something here onclickButton');
setContent('updated Value');
};
const resetColor = (value) => {
console.log(value);
setColor(value);
};
return (
<div data-testid='Component1'>
Component1
<button data-testid='button' onClick={onclickButton}>
Button
</button>
<div>Button Test :{content}</div>
<Select aria-label='select-Label' data-testid='select' options={options} value={color} onChange={resetColor} />
<div data-testid='color-value'>Current Color:{color}</div>
</div>
);
}
I did some reasearches , and they said the best way is mocked a select and test it:
beforeEach(() => {
render(<Component1 />);
});
test('should 3', () => {
jest.doMock('react-select', () => ({ options, value, onChange }) => {
function handleChange(event) {
const option = options.find((option) => option.value === event.currentTarget.value);
onChange(option);
}
return (
<select data-testid='custom-select' value={value} onChange={handleChange}>
{options.map(({ label, value }) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
);
});
fireEvent.change(screen.getByTestId('select'), {
target: { value: 'green' },
});
test('should 2', () => {
// screen.debug()
const onclickButton = jest.fn();
// render(<Component1 onclickButton={onclickButton} />);
fireEvent.click(screen.getByTestId('button'), {
// target: { value: 'JavaScript' },
});
});
after I run the test, I got this :
TestingLibraryElementError: Unable to find an element by: [data-testid="select"]
update:
I tried to use queryByLabelText, and it works, but still ,it seems not trigger the onChange event. I got this: Expected element to have text content: Current Color:green Received: Current Color:red
fireEvent.select(screen.queryByLabelText('select-Label'),{target:{value:'green'}})
expect(screen.queryByTestId('color-value')).toHaveTextContent('Current Color:green');
Upvotes: 1
Views: 2946
Reputation: 419
I resolved it by below code:
const DOWN_ARROW = { keyCode: 40 };
fireEvent.keyDown(screen.getByLabelText('select-Label'), DOWN_ARROW);
fireEvent.click(screen.getByText('Green'));
these code will trigger onChange event.
also refter to: how to test react-select with react-testing-library
Upvotes: 1