我在其他单元测试中遇到了丢失<router-outlet>
条消息的情况,但为了有一个很好的独立示例,我创建了一个AuthGuard,用于判断用户是否登录了某些操作.
以下是代码:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
现在我想为此编写一个单元测试.
以下是我开始测试的方式:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{
path: 'login',
component: DummyComponent
}
])
],
declarations: [
DummyComponent
],
providers: [
AuthGuardService,
{
provide: AuthService,
useClass: MockAuthService
}
]
});
});
我创建了一个DummyComponent,它什么都不做.
it('should not let users pass when not logged in', (): void => {
expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});
这将引发异常"找不到要加载的主出口".