Angular 检查是否调用了函数,角度单元测试

Angular 检查是否调用了函数,角度单元测试,angular,jasmine,Angular,Jasmine,我在ngOnInit中调用了一个函数 ngOnInit() { this.isSubscribable(); } 我想对这个ngOnInit进行单元测试,如下所示: it('Check isSubscribable is called from ngOnInit', async(async() => { spyOn(component, 'isSubscribable').and.callThrough(); fixture.detectChanges(

我在ngOnInit中调用了一个函数

ngOnInit() {
 this.isSubscribable();
}
我想对这个ngOnInit进行单元测试,如下所示:

    it('Check isSubscribable is called from ngOnInit', async(async() => {
      spyOn(component, 'isSubscribable').and.callThrough();
      fixture.detectChanges();
      await fixture.whenStable();
      expect(component.isSubscribable).toHaveBeenCalled();

    }))

这是行不通的。我需要一些帮助。

如果你这样做怎么办

it('从ngOnInit调用Check isSubscribable',()=>{
const spyssubscribable=spyOn(组件“isSubscribable”);
组件。ngOnInit();
expect(spySubscribable).toHaveBeenCalled();
});

如果你这样做怎么办

it('从ngOnInit调用Check isSubscribable',()=>{
const spyssubscribable=spyOn(组件“isSubscribable”);
组件。ngOnInit();
expect(spySubscribable).toHaveBeenCalled();
});
如果组件的
changeDetection
设置为
ChangeDetectionStrategy.OnPush,则只需手动调用
fixture.detectChanges()

假设您在
it
断言生效之前已正确实例化了组件,则上述操作应该有效,如:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
})
let组件:MyComponent;
let夹具:组件夹具;
在每个之前(()=>{
fixture=TestBed.createComponent(MyComponent);
组件=fixture.componentInstance;
})
如果您的代码非常简单,在
ngOnInit()
中只有此方法调用,那么您可能不需要使用任何
async/await
。whenStable
magic

如果组件的
changeDetection
设置为
ChangeDetectionStrategy.OnPush,则只需手动调用
fixture.detectChanges()

假设您在
it
断言生效之前已正确实例化了组件,则上述操作应该有效,如:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
})
let组件:MyComponent;
let夹具:组件夹具;
在每个之前(()=>{
fixture=TestBed.createComponent(MyComponent);
组件=fixture.componentInstance;
})

如果您的代码非常简单,在
ngOnInit()
中只有这个方法调用,那么您可能不需要使用任何
async/await
。whenStable
magic。

Error::应该是间谍,但得到了函数。用法:expect().tohavebeencall()位于Object.eval(./src/lib/custom ui compoyup,它可以工作,但为什么fixture.detectChanges不工作?我还不完全清楚。但我认为,鉴于您没有任何异步任务,您不需要检测更改,也不需要使用async/await.Error::预期是间谍,但获得了函数。用法:expect().toHaveBeenCalled()位于Object.eval(./src/lib/custom ui compoyup,它可以工作,但为什么fixture.detectChanges不工作?我还不完全清楚。但我认为,鉴于您没有任何异步任务,您也不需要检测更改来使用async/Wait。