Javascript 当激活的路由具有参数时调用函数时的角度测试
我正在尝试为一个组件编写一个测试,当activatedroute中有段Javascript 当激活的路由具有参数时调用函数时的角度测试,javascript,angular,typescript,jasmine,karma-jasmine,Javascript,Angular,Typescript,Jasmine,Karma Jasmine,我正在尝试为一个组件编写一个测试,当activatedroute中有段edit时调用函数 ngOnInit() { this.activatedRoute.url.subscribe((urlSegments) => { const currentRoute = urlSegments[0].path; console.log(currentRoute); if (currentRoute === "edit"
edit
时调用函数
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
函数,下面是我的测试
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模式为true,id也设置为123,但最后一个测试通过
expect(fixture.componentInstance.populateForm).toHaveBeenCalled()代码>未通过,我尝试使用fakeAsync
,whenStable
和flush()
但测试仍然失败,我不确定为什么
提前感谢夹具。检测更改()
不会触发ngonit
。您需要显式地调用它
it("should call populateForm when in edit mode", () => {
spyOn(fixture.componentInstance, "populateForm");
fixture.componentInstance.ngOnInit();
expect(fixture.componentInstance.populateForm).toHaveBeenCalledWith(123);
});
如果没有调用ngonit,那么其他测试是如何通过的?@WasifKhalil:当您在每个
块之前的中初始化组件时,它是第一次被调用的。@WasifKhalil:我建议的代码是否按预期工作?如果ngonit在之前被调用,那么它应该通过,仍然令人困惑,无论如何它工作了, thanks@WasifKhalil:它没有通过,因为您的spyOn
被放在了后面,这时ngOnInit
已经被调用了。因此,在spyOn
之后,您需要显式地调用