Angular Guard CanLoad单元测试

时间:2019-04-18 09:32:53

标签: angular jasmine angular7 angular-guards

我对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();
    }));

});

不允许我新建路线。我可能只是做错了测试。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

测试canLoad()

canActivate()不同,canLoad()仅需要Route参数。即canLoad(route: Route):booleancanActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot )Route只是我们用来定义和导出路由的接口,它应该已经存在于TestBed Module上下文中。因此,您根本不需要模拟它或创建它的新实例。


在您的beforeEach(async())茉莉函数中,导入带有路由的RouterTestingModule。

   TestBed.configureTestingModule({
      imports: [HttpClientModule, ... ..., RouterTestingModule.withRoutes(routes)],
      ...
      providers: [AuthenticationService, LoadGuard ] //only need to provide it here! 
   })

其中routes是您用export const routes: Routes = [{}]loadChildren定义的canLoad

请注意,自动导入RouterTestingModule 提供(即注入)以下服务:

  1. 位置
  2. LocationStrategy
  3. NgModuleFactoryLoader
  4. PreloadingStrategy
  5. 路由器

可以在以下API文档链接中看到:https://angular.io/api/router/testing/RouterTestingModule#providers

因此,您可以简单地引用这些注入的服务 而无需模拟

在describe()茉莉函数中,声明以下内容:

describe('AppComponent', () => {
   ... //all your other declarations like componentFixture, etc
   loadGuard: LoadGuard; 
   authService: AuthenticationService;
   router: Router;
   location: Location;
   loader: NgModuleFactoryLoader;
   ...
});

在您的beforeEach()茉莉函数中:

location = TestBed.get(Location); //these already exist in TestBed context because of RouterTestingModule
router = TestBed.get(Router);
... //other declarations
loadGuard = TestBed.get(LoadGuard);
authService = TestBed.get(AuthenticationService);

现在,此单元测试用例的目标是测试路由以及是否实际加载了相应的模块。

因此,您还需要在beforeEach()茉莉花函数中添加延迟加载的模块:

loader = TestBed.get(NgModuleFactoryLoader); //already exists in TestBed context because of RouterTestingModule

loader.stubbedModules = {
   './areas/home/home.module#HomeModule': HomeModule,
   ... //other lazily loaded modules 
}

fixture.detectChanges();

由于您已经如上所述将路由导入到configureTestingModule()中,因此无需重置路由器配置,因为API规范会将您设置为(https://angular.io/api/router/testing/SpyNgModuleFactoryLoader#description)。

所有设置完成后,您就可以测试canLoad()防护了。

it('if X claims is false, user shouldn't be able to load module', fakeAsync(() => {
   spyOn(authService, 'checkClaims').and.returnValue(false);
   fixture.detectChanges();

   router.navigateByUrl('XRoute');
   tick();
   expect(location.path()).toBe('/"unauthorised'); //or /404 depending on your req
}))

您不需要模拟其他任何东西,也不需要创建间谍对象。

尽管这个答案要迟几个月,而且很可能您现在甚至不需要它。我希望通过发布它可以对其他Angular开发人员有所帮助,因为这是Stackoverflow中唯一一个专门询问我也曾遇到过的单元测试canLoad()的问题。