I have an Angular authenticated
guard
@Injectable({
providedIn: 'root'
})
export class AuthenticatedGuard implements CanActivate, CanActivateChild {
constructor(@Inject('Window') private window: Window,
private readonly authenticationService: AuthenticationService) {}
canActivate(): boolean {
if (!this.authenticationService.isAuthenticated) {
this.window.location.href = '/login';
}
return allowed;
}
canActivateChild(): boolean {
return this.canActivate();
}
}
And I have these tests with a mock window I am injecting so that my test windoe doesn't redirect and so I can check to see if the href
is set
const MockWindow = {
location: {
_href: '',
set href(url: string) {
//console.log('set!', url)
this._href = url;
},
get href(): string {
//console.log('get!', this._href)
return this._href;
}
}
};
describe('Guard: authenticated', () => {
let redirectSpy: jasmine.Spy;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthenticatedGuard,
AuthenticationService,
{provide: 'Window', useValue: MockWindow}
]
});
redirectSpy = spyOnProperty(MockWindow.location, 'href', 'set');
});
afterEach(() => {
sessionStorage.removeItem('token');
});
it('should allow route activation when both the token is set', inject([AuthenticatedGuard], (guard: AuthenticatedGuard) => {
sessionStorage.setItem('token', 'foo');
expect(guard.canActivate()).toEqual(true);
expect(guard.canActivateChild()).toEqual(true);
expect(redirectSpy).not.toHaveBeenCalled();
}));
it('should disallow route activation when the token is not set', inject([AuthenticatedGuard], (guard: AuthenticatedGuard) => {
expect(guard.canActivate()).toEqual(false);
expect(guard.canActivateChild()).toEqual(false);
expect(redirectSpy).toHaveBeenCalledWith('/login'); //<-- this fails!
}));
...
The expect(redirectSpy).toHaveBeenCalledWith('/login');
always fails saying it was never called at all. Same with just expect(redirectSpy).toHaveBeenCalled();
- What am I doing wrong here? I want to be able to test this redirection, but I don't want my karma test browser to actually redirect.
(FYI: I need to use window.location.href
instead of the angular router so we can direct users to a different non-angular application that handles the login)