我有一个authenticated
角警卫队
@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();
}
}
我在注入的模拟窗口中进行了这些测试,以使测试窗口不会重定向,因此我可以检查href
是否已设置
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!
}));
...
expect(redirectSpy).toHaveBeenCalledWith('/login');
总是失败,它根本没有被调用。与expect(redirectSpy).toHaveBeenCalled();
相同-我在做什么错?我希望能够测试此重定向,但是我不希望我的业力测试浏览器实际重定向。
(仅供参考:我需要使用window.location.href
而不是角度路由器,以便我们可以将用户定向到处理登录的其他非角度应用程序)
答案 0 :(得分:0)
我发现一些有效的方法消除了间谍的需要。现在,我只是通过调用get
{@ 1}}从警卫那里注入了窗口提供程序,效果很好!
请让我知道是否可以做得更好!
TestBed.get('Window')