Angular 7 个单元测试 window.location.href

Angular 7 unit test with window.location.href

我正在尝试对我的 API 请求进行单元测试,以检查它是否 returns 预期结果。在 API 请求的回调中,我必须使用 window.location.href 将页面重定向到外部 url。 似乎测试用例试图重定向页面和 headless chrome returns 断开连接错误。我尝试创建模拟 window 服务,但仍然无法正常工作。


 this.apiSvc.logout().subscribe((res) => {
        localStorage.clear();
        window.location.href = res.url;
    })```

App.component.spec.ts

 it('should redirect to external page on clicking of logout function', async(() => { 
    spyOn(apiSvc, 'logout').and.callFake(() => {
      return of({url: mockWindow.location.href})
    })
    component.onLogout();
    expect(uiApiSvc.logout).toHaveBeenCalled();
  }));

Error message
Chrome 78.0.3904 (Windows 10.0.0): Executed 7 of 26 DISCONNECTED (30.567 secs / 0.722 secs)

在我看来,除了 window.location.href 的实际设置之外,您需要测试所有内容 - 您可以相信浏览器会正确执行此操作。我会将该部分包装在一个函数中,并检查函数本身是否使用正确的值调用:

public navigateToResponseUrl(url: string): void {
   window.location.href = url;
}

规格文件:

const navigateToResponseUrlSpy = spyOn(apiSvc, 'navigateToResponseUrl');
...
expect(navigateToResponseUrlSpy).toHaveBeenCalledWith('/your/url');