So basically when I'm trying to make use of the "fireEvent" method from React Testing Library it just gives me an error telling me the following:
MainSection.test.js:
test('Check SearchBar functionality', async () => {
render(<SearchBar />);
const textInput = screen.getByTestId('text-input');
fireEvent.change(textInput, { target: { value: 'mens cotton jacket' } });
});
SearchBar.js
import React from 'react';
import './SearchBar.css';
function SearchBar({ setSearch }) {
return (
<div className='search_bar'>
<input
type='text'
placeholder='Search here!'
className='search_bar-text'
data-testid='text-input'
onChange={e => setSearch(e.target.value)}></input>
</div>
);
}
export default SearchBar;
Also, when I delete the "onChange" event from the input text, the test just pass (aka green).
:/
CodePudding user response:
The issue to me appears to be that you're not providing the setSearch
prop. I think an appropriate test for this component would look like this:
it("sets search text", () => {
// mock out the work the parent component would
// ordinarily do to provide a `setSearch` prop
// by settting up a noop jest stub
const setSearch = jest.fn();
// note that we render w/ the setSearch prop
// provided here, so it's not `undefined` later
render(<SearchBar setSearch={setSearch} />);
// fire the event we want to test behaviours for
const textInput = screen.getByTestId('text-input');
fireEvent.change(textInput, { target: { value: 'mens cotton jacket' } });
// assert that `setSearch` was called how we expected
// as this is part of the component's public interface
expect(setSearch).toHaveBeenCalledTimes(1);
expect(setSearch).toHaveBeenCalledWith("mens cotton jacket");
});