Tengo un componente llamado componentA que muestra texto y un botón como este:
// 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>); } Quiero probar que al hacer clic en el botón, se llama a history.push con el argumento /new-route . Aquí está mi prueba:
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'); }); }); Esperaba que esto pasara porque la línea donde history.push imprimió que se llamaba, lo que significaba que history.push se ejecutó. Y cuando history.location.pathname también devolvió la ruta correcta. Sin embargo, la prueba aún falló con el mensaje:
expect(jest.fn()).toHaveBeenCalledWith(...expected) Number of calls: 0¿Alguien sabe por qué? Gracias