【发布时间】:2020-02-20 12:11:00
【问题描述】:
我在我的组件中插入了一个 if-else 条件,以便在登录后我将被转发到一个特定的 URL。但是,我的单元测试现在失败并出现以下错误:
1) 应该创建
另一个组件
Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'
没有 if else 条件一切正常,所以我确定这是我的问题的原因。有趣的是,我没有测试任何与我的 ngOnInit() 生命周期中的代码相关的东西。更有趣的是,不是 MyComponent 的测试失败了,而是另一个 Component 的测试失败了。
我的组件(MyComponent)长这样:
export class MyComponent implements OnInit {
routes = Constants.routes;
constructor(private router: Router,
private myService: MyService) {
}
ngOnInit() {
if (this.myService.context === 'TEST') {
this.router.navigate([routes.testroute + this.myService.context]);
} else {
this.router.navigate([routes.testroute]);
}
}
}
模板如下所示:
<router-outlet></router-outlet>
失败组件的单元测试如下所示:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([]),
],
providers: [
PathLocationStrategy
],
declarations: [AnotherComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AnotherComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
【问题讨论】:
标签: angular typescript unit-testing jasmine karma-jasmine