使用window.location.href进行7角单元测试 [英] Angular 7 unit test with window.location.href

查看:17
本文介绍了使用window.location.href进行7角单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


 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');

这篇关于使用window.location.href进行7角单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆