When I'm trying to test a window.open(url, '_blank')
, it'll automatically open a new tab in my browser during the testing. Is there any way I can prevent this from happening?
Like, try to open a new tab, but don't do it. I know you could do jasmine.createSpyObj('obj', ['methods']).and.returnValue({...})
, but I'm not sure how to do this for window.open
.
NavigationService
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 spec
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');
});
}
CodePudding user response:
The problem with your code is the using of callThrough method, which is responsible for opening the URL. Just remove it and it will resolve your issue.
Just use the below line:
windowSpy = spyOn(window, 'open');
Use of callthrough