I tried to test a required input field with React Testing Library and Jest by testing the existence of the popover, but I failed. I tried several variants and none is working. The steps from UI are the following:
- Click the empty field Empty select field
- Click next to the field (blur)
- Mouse over the field
- Get the required message Required message
The testing code for making that happen is:
const input = screen.getByRole('textbox', {name: /name \*/i})
expect(input).toBeTruthy();
fireEvent.click(input);
fireEvent.blur(input);
await waitFor(() => expect(input).toHaveValue(config.EMPTY_STRING));
act(() => {
fireEvent.mouseOver(input);
});
await waitFor(() => {
expect(screen.getByText('Name is required')).toBeTruthy();
});
Unfortunately, it doesn't work and I get this error: TestingLibraryElementError: Unable to find an element with the text: Name is required. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
I changed the last line this way: expect(screen.getByText('Name is required')).toBeInTheDocument();
but got the same error.
I tried with expect(screen.findByText('Name is required')).toBeInTheDocument();
but got the same error.
My last attempt was with: expect(screen.findByText('Name is required')).toBeTruthy();
. Here the test for the field passed but the overall test failed. The error I got is: console.error
Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one.
Error: Uncaught [TypeError: Cannot read property 'useRealTimers' of null]
So I got stucked. Any help would be much appreciated. Thanks a lot!
fireEvent
calls do not require you to wrap them inact
as that's already done internally by the library. – Pedicel