【问题标题】:Angular test failing : "Expected a spy, but got Function."Angular 测试失败:“预期是间谍,但得到了功能。”
【发布时间】:2021-12-29 09:33:54
【问题描述】:

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

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 test。当我将第二个测试称为“它”时出现错误:“预期是间谍,但得到了功能。”

编辑:这里是 beforeEach

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

我错过了什么?

【问题讨论】:

  • 你能显示beforeEaches和beforeAlls吗?
  • 是的,抱歉,我添加了。

标签: angular unit-testing karma-jasmine spy


【解决方案1】:

fixture.whenStable() 返回一个 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();
  });
});

【讨论】:

  • 工作得很好!非常感谢!
  • 不客气 :) 如果您将此标记为已接受的答案,我将不胜感激?
猜你喜欢
  • 2016-02-13
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
相关资源
最近更新 更多