检查函数是否被调用,Angular单元测试
Check if a function has been called, Angular unit testing
我在 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('Check isSubscribable is called from ngOnInit', () => {
const spySubscribable = spyOn(component, 'isSubscribable');
component.ngOnInit();
expect(spySubscribable).toHaveBeenCalled();
});
it('Check isSubscribable is called from ngOnInit', () => {
const spy = spyOn(component, 'isSubscribable').and.callThrough();
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
}))
如果您的组件将 changeDetection
设置为 ChangeDetectionStrategy.OnPush
,您只需手动调用 fixture.detectChanges()
。
假设您在 it
断言开始之前正确实例化了组件,以上内容应该可以工作,例如:
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
})
如果您的代码非常简单,在 ngOnInit()
中只有这个方法调用,那么您可能不需要使用任何 async/await
和 .whenStable
魔法。
我在 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('Check isSubscribable is called from ngOnInit', () => {
const spySubscribable = spyOn(component, 'isSubscribable');
component.ngOnInit();
expect(spySubscribable).toHaveBeenCalled();
});
it('Check isSubscribable is called from ngOnInit', () => {
const spy = spyOn(component, 'isSubscribable').and.callThrough();
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
}))
如果您的组件将 changeDetection
设置为 ChangeDetectionStrategy.OnPush
,您只需手动调用 fixture.detectChanges()
。
假设您在 it
断言开始之前正确实例化了组件,以上内容应该可以工作,例如:
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
})
如果您的代码非常简单,在 ngOnInit()
中只有这个方法调用,那么您可能不需要使用任何 async/await
和 .whenStable
魔法。