【问题标题】:Test onbeforeunload in Jest在 Jest 中测试 onbeforeunload
【发布时间】:2021-05-19 06:53:06
【问题描述】:

所以基本上我有一个 onbeforeunload 功能,如果他们决定重新加载或关闭标签,我会小心并警告用户。我的代码如下

  useEffect(() => {
   
    //this will prevent users from accidently refreshing / closing tab
    window.onbeforeunload = () => {
      return "Are you sure you want to do this yada yada yada yada?";
    };
  }, []);

我试图开玩笑地测试它,但 return 语句从未执行过。我的测试如下

window.location.reload();
expect(window.onbeforeunload).toHaveBeenCalled();

即使我模拟 onBeforeunload 它也不起作用。任何帮助都将不胜感激。谢谢。

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs gatsby


    【解决方案1】:

    您最好自己调度事件。

    window.dispatchEvent(new Event("beforeunload"));
    

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 2018-11-02
      • 2018-07-06
      • 2017-01-04
      • 2020-03-27
      • 2018-06-19
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多