[英]Angular test when a function is called when activated route has params
我正在嘗試為一個組件編寫測試,當 activatedroute 中有段edit
時調用 function
ngOnInit() {
this.activatedRoute.url.subscribe((urlSegments) => {
const currentRoute = urlSegments[0].path;
console.log(currentRoute);
if (currentRoute === "edit") {
this.isEdit = true;
this.id = params.id;
this.populateForm(this.id);
}
});
}
這是ngOnInit
function 下面是我的測試
beforeEach(() => {
mockNbToastrService = jasmine.createSpyObj(["show"]);
mockNbDialogService = jasmine.createSpyObj(["open"]);
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([]),
HttpClientTestingModule,
ReactiveFormsModule,
],
declarations: [ServiceCatalogComponent],
providers: [
{ provide: NbToastrService, useValue: mockNbToastrService },
{ provide: NbDialogService, useValue: mockNbDialogService },
{
provide: ActivatedRoute,
useValue: {
params: of({ id: 123 }),
url: of([
{
path: "edit",
},
]),
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(ServiceCatalogComponent);
fixture.detectChanges();
});
it("should be in edit mode", () => {
expect(fixture.componentInstance.isEdit).toBeTruthy();
})
it("should have an id if in edit mode", () => {
expect(fixture.componentInstance.id).toBe(123);
})
it("should call populateForm when in edit mode", () => {
spyOn(fixture.componentInstance, "populateForm");
fixture.detectChanges();
expect(fixture.componentInstance.populateForm).toHaveBeenCalled();
});
前兩個測試通過,其中 isEdit 模式為真且 id 也設置為 123,但最后一個測試
expect(fixture.componentInstance.populateForm).toHaveBeenCalled();
沒有通過,我嘗試使用fakeAsync
、 whenStable
和flush()
但測試仍然失敗我不確定為什么?
提前致謝
fixture.detectChanges fixture.detectChanges()
不會觸發ngOnInit
。 你需要明確地調用它
it("should call populateForm when in edit mode", () => {
spyOn(fixture.componentInstance, "populateForm");
fixture.componentInstance.ngOnInit();
expect(fixture.componentInstance.populateForm).toHaveBeenCalledWith(123);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.