如何测试Window beforeunload事件方法-角度单元测试

时间:2020-06-19 12:38:17

标签: angular unit-testing testing window onbeforeunload

我正在Angular 8项目中工作。

如果用户试图离开站点,我想让窗口抛出确认提示,我可以通过将此功能添加到组件中来做到这一点。

@HostListener("window:beforeunload", ["$event"])
  unloadNotification($event: any) {
    if (this.confirmNavigation) {
      $event.returnValue = true;
    }
  }

现在,我正在尝试找出如何对该单元进行测试,但我不确定该如何进行。我是否需要模拟窗口以触发事件?我会制作某种事件对象并直接调用它unloadNotification(虽然不确定如何验证结果)吗?

我什至确定在单元测试中是否需要这样做,这是否更像是集成测试?

我还需要确保当我在业力中运行测试时实际上并未触发此提示(因为它将停止测试)。所以我需要嘲笑吗?

此外,我想我想在每次测试后销毁此侦听器,但不确定如何做。

谢谢您的任何帮助。

1 个答案:

答案 0 :(得分:0)

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

具有unloadNotification方法的文件

     export abstract class ComponentCanDeactivate {
      abstract canDeactivate(): Observable<boolean>;
    
      constructor() { }
    
      @HostListener('window:beforeunload', ['$event'])
      async unloadNotification($event: any) {
        this.canDeactivate().subscribe(data => {
          if (data) {
            $event.returnValue = true;
          }
        });
      }

}

扩展抽象类的测试组件

@Component({
    selector: 'test-can-deactivate-mock-host',
    template: '<div></div>',
})
export class CanDeactivateTestComponent extends ComponentCanDeactivate {
    returnValue: boolean;

    constructor() {
        super();
    }

    canDeactivate(): Observable<boolean> {
        return of(this.returnValue);
    }
}

单元测试

describe('ComponentCanDeactivate', () => {
    let componentCanDeactivate: ComponentCanDeactivate;
    let canDeactivateTestComponent: CanDeactivateTestComponent;
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [MatDialogModule],
            providers: [
                ComponentCanDeactivate,
                CanDeactivateTestComponent
            ],
        });
        componentCanDeactivate = TestBed.get(ComponentCanDeactivate);
        canDeactivateTestComponent = TestBed.get(CanDeactivateTestComponent);
    });

    it('should be created', () => {
        expect(componentCanDeactivate).toBeDefined();
    });

    it('unloadNotification() should perform close event ', () => {
        const canDeactivateSpy = spyOn(canDeactivateTestComponent, 'canDeactivate').and.returnValue(of(true));
        canDeactivateTestComponent.unloadNotification({});
        expect(canDeactivateTestComponent).toBeDefined();
        expect(canDeactivateSpy).toHaveBeenCalled();
    });
});

相关问题