Having the following code:
import { useForm, Controller } from 'react-hook-form';
...
const { handleSubmit, reset, control, register, watch } = useForm({
resolver: yupResolver(schema)
});
const sensorOptions = [
{ id: '0', name: 'sensor 0' },
{ id: '1', name: 'sensor 1' },
{ id: '2', name: 'sensor 2' }
];
...
onSubmit={handleSubmit(onAddSubmit)} // the action when the submit is called
...
const onAddSubmit = (data) => {
postData(data); // the API call if all is good
toggle();
reset();
};
...
<div data-testid={TestIds.SENSOR}>
<Controller
control={control}
name='availableSensor'
render={({ field: { onChange } }) =>
<SelectInput
label='sensor')}
initialSelectedOption={{ id: '0', name: '' }}
onChange={onChange}
options={sensorOptions}
/>
}
/>
</div>
There are multiple SelectInputs like thi, but in this example it will be only one
const schema = yup.object().shape({
sensor: yup.object().shape({
id: yup.string(),
name: yup.string()
})
});
const { handleSubmit, reset, control, register, watch } = useForm({
resolver: yupResolver(schema)
});
And here is the test:
import { fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithClientInstance } from '../shared/test-utils';
import '@testing-library/jest-dom';
import MyModal from './my-modal';
describe('MyModal', () => {
const title = 'title';
const toggle = jest.fn();
const postData = jest.fn();
it('should call postData function on clicking in Save button successfully', async () => {
const { getByTestId, getByLabelText } = renderWithClientInstance(
<MyModal title={title} open={true} toggle={toggle} />
);
const saveButton = getByTestId('submit-button');
expect(saveButton).toBeInTheDocument();
userEvent.selectOptions(
getByLabelText('sensor'),
'sensor 0'
);
fireEvent.click(saveButton);
await waitFor(() => {
expect(postData).toBeCalled();
});
});
});
it fails with the error:
TestingLibraryElementError: Value "sensor 0" not found in options
idorname. Can you do one thing just putscreen.debug()in your test afterrenderremove everything else. You would importscreenfrom'@testing-library/react'selectDOM node, its made up ofdivs andspans. Let me add an answer then