Reputation: 584
I have the following test written with React Testing library. When I check it out in the browser, it works. However, here it doesn't work. What can be wrong?
it('Calls search callback on enter key press', () => {
const mockSearchCallback = jest.fn();
render(<Header onSearch={mockSearchCallback} />);
userEvent.type(screen.getByRole('textbox'), 'testquery');
userEvent.keyboard('{Enter}');
expect(mockSearchCallback).toHaveBeenCalled();
});
However, it fails.
Header
acts almost like a wrapper, all the logic is contained in Search.
Here's the code
export default function Search({ onSearch }: SearchProps) {
const [query, setQuery] = useState('');
const handleSubmit: React.FormEventHandler = (e) => {
e.preventDefault();
if (query) {
onSearch(query);
}
};
return (
<form className="c-search" onSubmit={handleSubmit}>
<input
className="c-search__input"
value={query}
onChange={(e) => setQuery(e.target.value)}
name="query"
autoComplete="off"
></input>
</form>
);
}
UPD It works with userEvent 13, but it doesn't with 14. Why?
Upvotes: 2
Views: 17217
Reputation: 6036
It looks like an issue with keyboard
for version 14.
I really dont know why this occuring but i will try to look depper into this later or even open a issue on testing-library/user-event
github.
But for now, you can accomplish this test with this:
it("Calls userEvent.type", async () => {
const mockSearchCallback = jest.fn();
render(<Header onSearch={mockSearchCallback} />);
const inputEl = screen.getByRole("textbox");
await userEvent.type(inputEl, "testquery{enter}");
expect(inputEl).toBeInTheDocument();
expect(inputEl).toHaveValue("testquery");
expect(mockSearchCallback).toHaveBeenCalledTimes(1);
});
So, i just call {enter}
from type
event.
You can check an example here -> Just click on Tests Tab.
Upvotes: 6