Angular 测试激活的路由有参数时调用函数的时间

Angular test when a function is called when activated route has params

我正在尝试为一个组件编写测试,其中当激活路由中有段 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 模式为真且 id 也设置为 123,但最后一个测试

expect(fixture.componentInstance.populateForm).toHaveBeenCalled(); 没有通过,我尝试使用 fakeAsyncwhenStableflush() 但测试仍然失败我不确定为什么?

提前致谢

fixture.detectChanges() 不触发 ngOnInit。你需要明确地调用它

  it("should call populateForm when in edit mode", () => {
    spyOn(fixture.componentInstance, "populateForm");
    fixture.componentInstance.ngOnInit();
    expect(fixture.componentInstance.populateForm).toHaveBeenCalledWith(123);
  });