Angular 测试失败:"Expected a spy, but got Function."

Angular test failing : "Expected a spy, but got Function."

我有这个测试,完美运行:

it('The click on the logo must call goTo("home")', () => {
  spyOn<LayoutComponent, any>(component, 'goTo');
  let logo = fixture.debugElement.query(
    By.css('#logoVitisoft')
  ).nativeElement;
  logo.click();
  fixture.whenStable().then(() => {
    expect(component.goTo).toHaveBeenCalledWith('home');
  });
});

而这个(与上一个几乎相同)触发了错误:

it('The click on Dashboard must call goTo(home)', () => {
  spyOn<LayoutComponent, any>(component, 'goTo');
  let button = fixture.debugElement.query(
    By.css('#dashboardElem')
  ).nativeElement;
  button.click();
  fixture.whenStable().then(() => {
    expect(component.goTo).toHaveBeenCalledWith('home'); /* ERROR SPAWN HERE */
  });
});

精度:如果用“fit”调用,则两个测试都通过了,我禁用了测试的随机性,并继续使用相同的种子执行 ng 测试。当我将第二个测试称为“它”时出现错误:“预期是间谍,但得到了功能。”

编辑:这里是 beforeEach

beforeEach(async () => {
 await TestBed.configureTestingModule({
  imports: [RouterTestingModule, HttpClientModule],
  declarations: [LayoutComponent],
 }).compileComponents();
});
beforeEach(() => {
 fixture = TestBed.createComponent(LayoutComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
});

我错过了什么?

fixture.whenStable() returns一个Promise,异步执行。这意味着您的测试已经完成并在执行 expect() 时进行了清理。

尝试使用 done() 函数进行这些类型的测试:

it('The click on Dashboard must call goTo(home)', (done) => {
  spyOn<LayoutComponent, any>(component, 'goTo');
  let button = fixture.debugElement.query(
    By.css('#dashboardElem')
  ).nativeElement;
  button.click();
  fixture.whenStable().then(() => {
    expect(component.goTo).toHaveBeenCalledWith('home');
    done();
  });
});