我对 Angular 7 比较陌生,来自 AngularJS,我编写了一个实现 CanLoad 的守卫,它在没有正确声明加载模块的情况下阻止用户。它检查用户是否已登录以及用户是否有路由所期望的声明。
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoadGuard } from './core/authentication/guards/load.guard';
import { MainMenuComponent } from './core/navigation/main-menu/main-menu.component';
import { PageNotFoundComponent } from './core/navigation/page-not-found/page-not-found.component';
import { UnauthorisedComponent } from './core/navigation/unauthorised/unauthorised.component';
const routes: Routes = [
{ path:'', component: MainMenuComponent, outlet: 'menu'},
{ path: 'authentication', loadChildren: './core/authentication/authentication.module#AuthenticationModule' },
{ path: 'home', loadChildren: './areas/home/home.module#HomeModule', canLoad: [LoadGuard], data: {expectedClaim: 'home'} },
{ path:"unauthorised", component: UnauthorisedComponent},
{ path:'**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
守卫工作,但是我在为它编写单元测试时遇到了麻烦。
import { Injectable } from '@angular/core';
import { CanLoad, Route, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from 'src/app/Services/Authentication/authentication.service';
@Injectable({
providedIn: 'root'
})
export class LoadGuard implements CanLoad {
constructor(private authService: AuthenticationService, private router: Router){}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
if (!route || !route.path) return false;
let isValid: boolean = this.checkLoggedIn(route.path);
if (isValid) {
if (route.data && route.data.expectedClaim) {
let expectedClaim = route.data.expectedClaim;
isValid = this.checkClaim(expectedClaim);
}
}
return isValid;
}
checkLoggedIn(url: string): boolean {
if (this.authService.checkLoggedIn()) {
return true;
}
this.authService.redirectUrl = url;
console.log('this.authService.redirectUrl (after)= ' + this.authService.redirectUrl);
this.router.navigate(['/authentication/login']);
return false;
}
checkClaim(claim: string) {
let hasClaim: boolean = false;
if (this.authService.currentUser) {
hasClaim = this.authService.currentUser.claims.indexOf(claim) > -1;
}
return hasClaim;
}
}
我在下面的单元测试不起作用:
import { HttpClientModule } from '@angular/common/http';
import { fakeAsync, TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, ActivatedRoute, Route } from '@angular/router';
import { LoadGuard } from './load.guard';
class MockActivatedRouteSnapshot {
private _data: any;
get data(){
return this._data;
}
}
let mockRouterStateSnapshot : RouterStateSnapshot;
describe('LoadGuard', () => {
let loadGuard: LoadGuard;
let route: ActivatedRouteSnapshot;
let authService;
let mockRouter: any;
beforeEach(() => {
mockRouter = jasmine.createSpyObj('Router', ['navigate']);
TestBed.configureTestingModule({
imports: [
HttpClientModule,
],
providers: [
LoadGuard,
{ provide: ActivatedRouteSnapshot, useClass: MockActivatedRouteSnapshot},
{ provide: Router, useValue: mockRouter},
]
});
});
it('should be created', () => {
authService = { checkLoggedIn: () => true };
loadGuard = new LoadGuard(authService, mockRouter);
expect(loadGuard).toBeTruthy();
});
describe('check expected claims', ()=>{
it('should not be able to load an valid route needing claim when logged in without claim', fakeAsync(() => {
authService = { checkLoggedIn: () => true };
loadGuard = new LoadGuard(authService, mockRouter);
let route = new Route();
spyOnProperty(route,'data','get').and.returnValue({expectedClaim: 'policy'});
mockRouterStateSnapshot = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', ['toString']);
mockRouterStateSnapshot.url = "test";
expect(loadGuard.canLoad(route)).toBeFalsy();
}));
});
它不允许我新建一条路线。我可能只是做错了测试。有人能帮忙吗?