如何防止window.open(url,'_blank')在Jasmine单元测试期间实际打开



当我尝试测试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;
}
...
}
}

导航服务规范

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

代码的问题是使用了callThrough方法,该方法负责打开URL。只要删除它,它就会解决您的问题。

只需使用以下行:

windowSpy = spyOn(window, 'open');

使用直通

最新更新