Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在卸载事件方法之前测试窗口-角度单元测试_Angular_Unit Testing_Testing_Window_Onbeforeunload - Fatal编程技术网

Angular 如何在卸载事件方法之前测试窗口-角度单元测试

Angular 如何在卸载事件方法之前测试窗口-角度单元测试,angular,unit-testing,testing,window,onbeforeunload,Angular,Unit Testing,Testing,Window,Onbeforeunload,我在一个角度8的项目中工作 我想让窗口在用户试图离开站点时抛出一个确认提示,我可以通过将此函数添加到我的组件来实现这一点 @HostListener("window:beforeunload", ["$event"]) unloadNotification($event: any) { if (this.confirmNavigation) { $event.returnValue = true; } } 现在我正试图找出如何进行单元测试,但我不确定如何进行

我在一个角度8的项目中工作

我想让窗口在用户试图离开站点时抛出一个确认提示,我可以通过将此函数添加到我的组件来实现这一点

@HostListener("window:beforeunload", ["$event"])
  unloadNotification($event: any) {
    if (this.confirmNavigation) {
      $event.returnValue = true;
    }
  }
现在我正试图找出如何进行单元测试,但我不确定如何进行。我是否需要模拟窗口以触发事件?我会制作某种类型的事件对象并直接使用它调用
unloadNotification
(但不知道如何验证它的结果)

我甚至可以肯定,如果在单元测试中需要这样做,它会更像一个集成测试吗

我还需要确保在karma中运行测试时不会触发此提示(因为它会停止测试)。所以我需要嘲笑一下

此外,我想在每次测试后都要销毁这个侦听器,但不确定如何销毁


非常感谢您的帮助。

此单元测试解决方案使用模拟概念。如果具有卸载通知的方法是抽象类,则此解决方案有效。并在另一个组件中扩展

@HostListener("window:beforeunload", ["$event"])
  unloadNotification($event: any) {
    if (this.confirmNavigation) {
      $event.returnValue = true;
    }
  }
具有unloadNotification方法的文件

导出抽象类ComponentCanDeactivate{
抽象canDeactivate():可观察;
构造函数(){}
@HostListener('window:beforeunload',['$event']))
异步卸载通知($event:any){
this.canDeactivate().subscribe(数据=>{
如果(数据){
$event.returnValue=true;
}
});
}
}
this.canDeactivate();构造函数体或ngOnInit(){}中缺少,这是@Ashwin提供的非常优雅的解决方案,谢谢!对它的测试节省了我很多时间,而且管理这个抽象类真是太棒了