测试组件方法调用另一个方法

testing that a component method calls another method

给定这个简单的组件:

import { Component} from '@angular/core';

@Component({
  selector: 'app-component'
})
export class AppComponent {
  foo() {
    this.bar();
  }

  bar() {
    console.log('hello');
  }
}

当我调用 foo

时,为什么下面的测试无法验证 bar 被调用了
describe('AppComponent', () => {
  let component: AppComponent;

    beforeEach(() => {
    component = new AppComponent();
  }

  it('should foobar', () => {
    component.foo();
    spyOn(component, 'bar');
    expect(component.bar).toHaveBeenCalled();
  })

}

我得到失败的测试:

Expected spy bar to have been called.

您需要在调用该方法之前设置间谍。 Jasmine 监视包装函数以确定它们何时被调用以及它们被调用的内容。为了捕获信息,必须在调用监视方法之前包装该方法。尝试更改您的测试以匹配以下内容:

it('should foobar', () => {
    spyOn(component, 'bar');
    component.foo();
    expect(component.bar).toHaveBeenCalled();
})
it("should foobar", () => {
    const spy = spyOn(component, "bar");
    component.foo();
    expect(spy).toHaveBeenCalled();
  });