首页 > 解决方案 > 使用@testing-library/user-event 进行虚假点击

问题描述

我想测试单击反应中的链接时是否发生跟踪事件。但是,我确实得到了Error: Not implemented: navigation单击链接时发生的情况的影响。我正在用 jest 和@testing-library/user-event 进行测试

我现在想模拟或存根,以便在触发 userEvent 时不会发生导航尝试,因为我只想看到正在发生的跟踪事件。我怎样才能做到这一点?

userEvent.click(item);

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

标签: javascriptreactjsjestjsreact-testing-libraryuser-event

解决方案


我认为您的测试实际上是在尝试使用 window.location 进行导航

在尝试用户事件之前,您需要模拟它

let assignMock = jest.fn();

delete window.location;
window.location = { assign: assignMock };

afterEach(() => {
  assignMock.mockClear();
});

推荐阅读