Error when testing a React search component

Hi I´m getting this TypeError when testing my component, I don't know why the history is undefined

TypeError: Cannot read property 'push' of undefined

      16 |     e.preventDefault();
      17 |     setSearchTerm(inputValue);
    > 18 |     history.push(`/search/${inputValue}`);

here is my component:

  const handleSubmit = (e) => {
e.preventDefault();
setSearchTerm(inputValue);
history.push(`/search/${inputValue}`);

and my test

  it("Calls the handleSubmit function", () => {
const handleSubmit = jest.fn();
fireEvent.submit(screen.getByRole("textbox"));
expect(handleSubmit).toHaveBeenCalled();

1 answer

  • answered 2021-04-14 22:53 unclebay143

    are you using a functional component or class component?

    if functional component

    do

    import { useHistory} from "react-router-dom";
    
    const YourComponent = () =>{
    
    const history = useHistory();
    
    const handleSubmit = (e) => {
      e.preventDefault();
      setSearchTerm(inputValue);
      history.push(`/search/${inputValue}`);
    
    return(<button onClick={()=>handleSubmit()}>Submit</button>)
    
    }