javascriptreactjsjestjsreact-testing-libraryuser-event

Fake click using @testing-library/user-event


I want to test that a tracking event occurs when clicking a link in react. However I do get a Error: Not implemented: navigation as an effect of what happens when the link is clicked. I am testing with jest and @testing-library/user-event.

I now want to mock or stub so that no navigation attempt takes place when the userEvent is fired as I am only interested to see the tracking event taking place. How can I do this?

userEvent.click(item);

expect(Ga.trackEvent).toHaveBeenCalledTimes(1);
expect(Ga.trackEvent).toHaveBeenCalledWith('myModal', 'open'); 


Solution

  • I think your test is actually trying to navigate using window.location

    You will need to mock that out before trying the user event

    let assignMock = jest.fn();
    
    delete window.location;
    window.location = { assign: assignMock };
    
    afterEach(() => {
      assignMock.mockClear();
    });