【发布时间】:2020-08-18 05:01:00
【问题描述】:
我正在尝试在名为 UserComponent 的 Angular 组件上运行业力测试。在这个组件中,我有一个我的 ngOnInit 这样做:
ngOnInit() {
const stream = this.tokenSvc.authTokens.pipe(switchMap((x) => {
this.infoSvc.fetchUserInfo().toPromise().then((y) => {
localStorage.setItem("oauth", this.tokenSvc.oAuthToken);
localStorage.setItem("username", y["id"]);
this.infoSvc.updateAlbums()
this.infoSvc.login(y["id"], this.tokenSvc.oAuthToken).toPromise().then((z) => {
this.router.navigate(['home']);
})
}).catch((e) => {
console.log("unable to fetch user data")
});
return this.infoSvc.fetchUserInfo();
}));
this.stream = stream.subscribe((x) =>
this.user = x
)
}
错误的关键是this.router.navigate(['home']); 行。由于某种原因,它无法将 home 与我的路由中的组件匹配。不过,该组件在我的路由中:
{
path:'home',
component: HomeComponent,
canActivate: [
AuthGuard
]
}
在我的测试中,我读到 this stackoverflow post 说尝试将 withRoutes 添加到测试中,尽管这不起作用。这是我的测试代码
describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ FaIconComponent, AlbumInfoComponent, UserComponent, HomeComponent, SearchBarComponent, RecentReleaseComponent, YourQueueComponent ],
imports: [FormsModule , HttpClientTestingModule, RouterTestingModule.withRoutes([{path: 'home', component: HomeComponent}])],
providers: [AuthService, TokenService, InfoService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在那里,您可以看到我尝试使用 withRoutes 并添加路径和组件覆盖,但运气不佳。这是完整的错误:
Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'
【问题讨论】:
标签: javascript angular testing jasmine karma-runner