【发布时间】:2018-12-30 23:42:26
【问题描述】:
我有一个离子项目,该项目在组件的构造函数中具有一个方法,该方法根据条件调用。我正在使用 Jasmine,我想监视该方法以检查它是否被调用。
这是组件的构造函数:
export class MyComponent {
public test: boolean;
constructor(public service: MyService) {
if(test) {
service.getX();
}
}
}
在我的 spec.ts 中,我必须实例化组件才能窥探该方法,但由于该方法已在构造函数中调用,因此无法正常工作。
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('Test case #1', () => {
component.test = true;
spyOn(component.service, 'getX'); //The method has already been called in the constructor called in beforEach above
expect(component.service.getX).toHaveBeenCalled();
})
如何监视构造函数中调用的方法?
【问题讨论】:
-
你需要创建一个模拟服务而不是监视真实的服务。
标签: angular typescript unit-testing ionic-framework jasmine