I have this function I need to test:
login(): void {
this.userService.setSessionAndDateOnlogin();
this.loginService.getLogin()
.subscribe(
octopusUrl => window.location.href = octopusUrl);
}
I use the window.location.href to navigate to an external URL.
This is my test:
it('login function should call the setSessionAndDateOnLogin function from the userservice and\
subscribe to the getLogin function of the loginService.',
fakeAsync(
inject(
[LoginComponent, LoginService, UserService],
(loginComponent: LoginComponent, loginService: LoginService, userService: UserService) => {
spyOn(userService, 'setSessionAndDateOnlogin');
loginComponent.login();
expect(userService.setSessionAndDateOnlogin).toHaveBeenCalled();
})
)
);
When I run this test, I get the following error:
Some of your tests did a full page reload!
So I tried to mock the window-object:
import { window } from '@angular/platform-browser/src/facade/browser';
...
class MockWindow {
location: {
href: ''
};
}
...
beforeEach(() => addProviders([
...
{ provide: window, useClass: MockWindow }
]));
This changed nothing and the error remains.
Does anyone has a solution for this issue?
Window is an interface and that cannot be injected. You should use OpaqueToken
import {Injectable, OpaqueToken, Inject} from '@angular/core';
export const WindowToken = new OpaqueToken('Window');
export const SomeServiceWithWindowDependencyToken = new OpaqueToken('SomeServiceWithWindowDependency');
export function _window(): Window {
return window;
}
export class SomeServiceWithWindowDependency {
private window: Window;
constructor(@Inject(WindowToken) window: Window) {
this.window = window;
}
}
Then in tests
describe('SomeServiceWithWindowDependency', () => {
beforeEach(() => {
let mockWindow: any = {
location: {
hostname: ''
}
};
TestBed.configureTestingModule({
providers: [
{provide: WindowToken, useValue: mockWindow},
{provide: SomeServiceWithWindowDependencyToken, useClass: SomeServiceWithWindowDependency}
]
});
});
it('should do something', inject([SomeServiceWithWindowDependencyToken, WindowToken], (tested: SomeServiceWithWindowDependency, window: Window) => {
window.location.hostname = 'localhost';
expect(tested.someMethod()).toBe('result');
}));
});
And remember to configure app module to use real window object
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
...
{provide: WindowToken, useFactory: _window},
],
bootstrap: [AppComponent]
})
export class AppModule {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With