【发布时间】:2017-07-03 08:23:24
【问题描述】:
我有一个AuthGuard 服务负责检测用户是否已登录。如果未登录,我会将用户重定向到我们的 oauth 提供程序 url。
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { environment } from './../../environments/environment';
import { Session } from './../core/security/session.service';
@Injectable()
export class AuthGuard implements CanActivate {
/**
* Class constructor.
* @constructor
*
* @param {Session} - Instance of session.
*/
constructor(private session: Session) {}
/**
* Method to implements from CanActivate interface.
* Check if a user is authenticated.
*
* @return {boolean}
*/
canActivate(): boolean {
if (this.session.isActive()) {
return true;
}
this.redirectToProvider();
return false;
}
/**
* Redirect to Identity unauthorized url.
*/
private redirectToProvider() {
const unauthorizeUrl = environment.api.identity.unauthorizeUrl;
window.location.href = unauthorizeUrl;
}
}
我想知道当会话不存在时是否调用了window.location.href。这是我到目前为止所做的:
import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AuthGuard } from './auth-guard.service';
import { Session } from './../core/security/session.service';
describe('AuthGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthGuard,
Session
],
imports: [RouterTestingModule]
});
});
describe('.canActivate', () => {
describe('active session', () => {
it('returns true',
async(inject([AuthGuard, Session], (guard, session) => {
session.set({ name: 'user' });
expect(guard.canActivate()).toBeTruthy();
})
));
});
describe('no session', () => {
it('redirects the user',
async(inject([AuthGuard, Session], (guard, session) => {
spyOn(window.location, 'href');
session.destroy();
expect(guard.canActivate()).toBeFalsy();
expect(window.location.href).toHaveBeenCalled();
})
));
});
})
});
但它给了我以下错误:
Failed: <spyOn> : href is not declared writable or has no setter
有没有办法模拟窗口对象来实现这一点,还是我需要依赖一些特殊的类来处理这种重定向,以便我可以在测试中注入它们?
【问题讨论】:
-
为什么不使用 this.router.navigate 或 this.router.navigateByUrl 而不是 window.location.href
-
我试过了,但
this.router.navigateByUrl似乎只适用于 Angular 注册的路由。但是,就我而言,我正在尝试重定向到外部 url。