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