如何测试我的Angular 8应用程序使用了防护(但不测试防护)?

时间:2019-10-17 14:05:29

标签: angular angular-routing

我有一个保护措施,可防止任何用户在未登录的情况下使用该应用程序。

保护程序位于其自己的模块中,与我的应用程序分开。因此,我不想测试防护本身,而是要使用它。需要说明的是:如果有人错误地从路由器中删除了canActivate: [MyGuard],行,否则我通过了测试。

我认为这样做的方法是监视防护装置的canActivate方法,然后将该防护装置注入路由器。

但是我无法成功完成,从搜索中发现的每个结果都集中在测试守卫本身。

这就是我现在所拥有的,当然会失败,因为根本没有真正使用过路由器:

// app.routing.ts
const routes: Routes = [
  {
    path: '',
    canActivate: [IsAuthenticatedGuard], // this is what I want to make sure is present
    children: [{ path: '', pathMatch: 'full', component: HomeComponent }],
  },
];
// myspec.spec.ts
describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let canActivateSpy: jasmine.Spy;
  let isAuthenticatedGuard: IsAuthenticatedGuard;

  beforeAll(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        ..., // a bunch of other imports that aren't relevant to that question
      ],
      declarations: [AppComponent],
    });
    fixture = TestBed.createComponent(AppComponent);
    isAuthenticatedGuard = fixture.debugElement.injector.get(
      IsAuthenticatedGuard,
    );
    canActivateSpy = spyOn(isAuthenticatedGuard, 'canActivate');
    fixture.detectChanges();
    component = fixture.componentInstance;
  }));

  it('should have a guard', () => {
    expect(canActivateSpy.calls.any()).toBe(true);
  });

我将如何使用Angular 8进行测试?

0 个答案:

没有答案