Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
jest testing mock history.push not called even though it was called in the component

I have a component called componentA that render some text and a button like this:

// Do some import statements
// ComponentA
function ComponentA() {
  const [submitState, setState] = useState(false);
  useEffect(()=> {
   if (submitState) {
     console.log("history.push called");
     history.push('/new-route');
   }
  }) 

  return ( <div>Hello 
  <Button onClick ={()=> setState(true}> Click here </Button>  
  </div>);
}

I want to test that upon clicking the button, history.push is called with the argument /new-route. Here is my testing:

import {render} from '@testing-library/react'

describe("Test Component A", () => {
  const history = createMemoryHistory();
  const pushSpy = jest.spyOn(history, 'push');

  test("it should call history.push with correct argument", async () => {
     //render componentA
      const {container} = render(<ComponentA  />)
     // Point B: click
     fireEvent.click(screen.getByText('Click here'));
     // Poin C: assert that the history.push is called
      expect(pushSpy).toHaveBeenCalledWith('/new-route');
  });
});

I expected this to pass because the line where the history.push did print out that it was called which meant history.push did run. And when I printed out history.location.pathname it also returned the correct route. However the test still failed with the message:

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Number of calls: 0

Anyone knows why ? Thank you

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!