如何防止 window.open(url, '_blank') 在茉莉花单元测试期间实际打开
How to prevent window.open(url, '_blank') to actually open during jasmine unit test
当我尝试测试 window.open(url, '_blank')
时,它会在测试期间自动在我的浏览器中打开一个新选项卡。有什么办法可以防止这种情况发生吗?
喜欢,尝试打开一个新标签,但不要这样做。我知道你可以做到 jasmine.createSpyObj('obj', ['methods']).and.returnValue({...})
,但我不确定如何做到 window.open
。
导航服务
export class NavigationService {
navigate(url: string, openInNewTab: boolean = false): boolean {
if (url.startsWith('http')) {
openInNewTab ? window.open(url, '_blank') : ((window as any).location.href = url);
return false;
}
...
}
}
NavigationService 规范
describe('NavigationService', () => {
let navigationService: NavigationService;
let routerSpy, configServiceSpy, windowSpy;
let httpUrlMock = 'http://mock.com';
beforeEach(() => {
routerSpy = jasmine.createSpyObj('Router', ['createUrlTree', 'navigateByUrl']);
configServiceSpy = jasmine.createSpyObj('ConfigService', ['current']);
windowSpy = spyOn(window, 'open').and.callThrough();
navigationService = new NavigationService(routerSpy, configServiceSpy);
});
it('should open the url in a new tab when the url starts with http ', () => {
let _result = navigationService.navigate(httpUrlMock, true);
expect(windowSpy).toHaveBeenCalledWith(httpUrlMock, '_blank');
});
}
您的代码的问题在于使用了负责打开 URL 的 callThrough 方法。只需将其删除即可解决您的问题。
只需使用下面一行:
windowSpy = spyOn(window, 'open');
当我尝试测试 window.open(url, '_blank')
时,它会在测试期间自动在我的浏览器中打开一个新选项卡。有什么办法可以防止这种情况发生吗?
喜欢,尝试打开一个新标签,但不要这样做。我知道你可以做到 jasmine.createSpyObj('obj', ['methods']).and.returnValue({...})
,但我不确定如何做到 window.open
。
导航服务
export class NavigationService {
navigate(url: string, openInNewTab: boolean = false): boolean {
if (url.startsWith('http')) {
openInNewTab ? window.open(url, '_blank') : ((window as any).location.href = url);
return false;
}
...
}
}
NavigationService 规范
describe('NavigationService', () => {
let navigationService: NavigationService;
let routerSpy, configServiceSpy, windowSpy;
let httpUrlMock = 'http://mock.com';
beforeEach(() => {
routerSpy = jasmine.createSpyObj('Router', ['createUrlTree', 'navigateByUrl']);
configServiceSpy = jasmine.createSpyObj('ConfigService', ['current']);
windowSpy = spyOn(window, 'open').and.callThrough();
navigationService = new NavigationService(routerSpy, configServiceSpy);
});
it('should open the url in a new tab when the url starts with http ', () => {
let _result = navigationService.navigate(httpUrlMock, true);
expect(windowSpy).toHaveBeenCalledWith(httpUrlMock, '_blank');
});
}
您的代码的问题在于使用了负责打开 URL 的 callThrough 方法。只需将其删除即可解决您的问题。
只需使用下面一行:
windowSpy = spyOn(window, 'open');