【发布时间】:2017-06-09 04:57:03
【问题描述】:
我正在尝试为调用 router.navigate() 的组件编写一些测试,但在声明路由时遇到了错误。我已经阅读了很多东西并尝试了所有这些,但它们都会导致一些错误或其他错误。我正在使用 Angular 4.0.0。
组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private authService: AuthService,
private formBuilder: FormBuilder,
private jwtService: JwtService,
private router: Router,
private storageService: StorageService
) { ... }
ngOnInit() {
}
private login(formData: any): void {
const credentials: any = {
email: formData.controls.email.value,
password: formData.controls.password.value
};
this.authService.login(credentials).subscribe(res => {
this.activatedRoute.params.subscribe(params => {
if (params.returnUrl) {
this.router.navigate([params.returnUrl]);
} else {
this.router.navigate(['/dashboard']);
}
});
}, error => { ... });
}
}
测试:
describe('LoginComponent', () => {
let component: any;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [
SharedModule,
RouterTestingModule
],
providers: [{
provide: AuthService,
useClass: MockAuthService
}, {
provide: JwtService,
useClass: MockJwtService
}, {
provide: StorageService,
useClass: MockStorageService
}],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('login', () => {
it('should call router.navigate with the dashboard route if the login is successful', () => {
spyOn(component.router, 'navigate');
component.authService.login.and.returnValue(Observable.of({ access_token: 'fake_token' }));
component.login(component.loginForm);
expect(component.router.navigate).toHaveBeenCalledWith(['/dashboard']);
});
});
});
这一切都给了我以下错误:
zone.js:569 未处理的承诺拒绝:无法匹配任何路由。 URL 段:“仪表板”
所以我从那里开始考虑使用withRoutes 添加路线。我不喜欢我需要包含DashboardComponent,因为似乎应该有一些可用的模拟/空白组件,特别是因为我不想实际导航和加载另一条路线,但我找不到任何东西像这样:
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [
SharedModule,
RouterTestingModule.withRoutes([{
path: 'dashboard',
component: DashboardComponent
}])
],
...
})
.compileComponents();
但是这只是给我一个新的错误:
Component DashboardComponent 不是任何 NgModule 的一部分,或者该模块尚未导入到您的模块中。
所以我想也许我需要声明DashboardComponent,所以我将它添加到声明数组中:
TestBed.configureTestingModule({
declarations: [ LoginComponent, DashboardComponent ],
..
})
.compileComponents();
然而,这只会导致另一个错误:
未处理的承诺拒绝:找不到加载“仪表板组件”的主要出口
在这一点上,似乎必须有一种更简单的方法来做到这一点,因为这是一种非常常见的情况,但我已经尝试了其他人说他们使用过的所有方法,而且一切都让这个兔子洞更进一步。
【问题讨论】:
标签: angular karma-jasmine