给定这个简单的组件:
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.
最佳答案
您需要在调用该方法之前设置 spy 。 Jasmine 监视包装函数以确定它们何时被调用以及它们被调用的内容。为了捕获信息,必须在调用监视方法之前包装该方法。尝试更改您的测试以匹配以下内容:
it('should foobar', () => {
spyOn(component, 'bar');
component.foo();
expect(component.bar).toHaveBeenCalled();
})
关于angular - 测试组件方法调用另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302114/