[英]Unit testing Angular with Karma/Jasmine:
我在我的組件中插入了一個 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();
});
導入路由器測試模塊時需要配置路由。 我通常使用虛擬組件設置路由。
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([
// add routes here
{ path: 'testroute', component: DummyComponent }
]),
],
providers: [
PathLocationStrategy
],
declarations: [AnotherComponent],
}).compileComponents();
@Component({ template: '' })
class DummyComponent { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.