I have this functional component.
Search.js
function Search() {
const [term, setTerm] = useState('sun');
function handleOnChange(e) {
if (!e.target.value) {
return false;
}
setTerm(e.target.value);
return true;
}
return <input type="text" onChange={handleOnChange} placeholder="Search" />
}
Search.test.js
import { render, fireEvent } from '@testing-library/react';
import Search from '.';
describe('when type a valid term', () => {
it('update the state', () => {
const { getByPlaceholderText } = render(<Search />;
// this doesn't work. The handleOnChange method is private. How to deal with this?
const handlerSpy = jest.spyOn(Search, 'handleOnChange');
fireEvent.click(getByPlaceholderText(/search/i), { target: { value: 'moon' } });
expect(handlerSpy).toHaveReturnedWith(true);
});
});
I don't know if I'm trying the wrong approach. I just need to test what happens if the user type an empty term. Appreciate any suggestion.