[英]Angular Testing: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
I am trying to run karma tests on an Angular component called UserComponent
.我正在尝试在名为
UserComponent
的 Angular 组件上运行业力测试。 In this component, I have a my ngOnInit doing this:在这个组件中,我有一个我的 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
)
}
The key to the error is the this.router.navigate(['home']);
错误的关键是
this.router.navigate(['home']);
line.线。 For some reason it can't match home to a component from my routing.
由于某种原因,它无法将 home 与我的路由中的组件匹配。 Though, the component is in my routing:
虽然,该组件在我的路由中:
{
path:'home',
component: HomeComponent,
canActivate: [
AuthGuard
]
}
In my testing, I read this stackoverflow post that said to try adding the withRoutes to the test, though this didn't work.在我的测试中,我阅读了这篇 stackoverflow 帖子,上面说尝试将 withRoutes 添加到测试中,尽管这不起作用。 Here is my testing code
这是我的测试代码
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();
});
});
There, you can see me try the withRoutes and add path and component overrides to no luck.在那里,您可以看到我尝试使用 withRoutes 并将路径和组件覆盖添加到不走运。 Here is the full error:
这是完整的错误:
Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home'
Error: Cannot match any routes. URL Segment: 'home'
You need to initialize the router into your test suite:您需要将路由器初始化到您的测试套件中:
// add a router declaration at the top of your describe
let router: Router;
// enhance your second beforeEach by instancing the router and initializing the navigation
beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
router = TestBed.get(Router);
router.initialNavigation();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.