我在组件中有以下功能。
@Output() data: EventEmitter<any> = new EventEmitter();
testData() {
observableRef.subscribe(() => {
this.data.emit();
}, () => {
this.data.emit();
});
}
我想为上述函数编写单元测试用例,我尝试过如下:
it('should call testData method', fakeAsync(() => {
fixture.detectChanges();
spyOn(observableRef, 'emit’);
component.testData(component.data);
expect(component.data.emit).toHaveBeenCalled();
tick();
discardPeriodicTasks();
}));
但是,在运行此测试用例后,代码覆盖率不会进入 subscribe 函数内部。我不知道为什么,实际上我是这个单元测试的新手,任何人都可以帮助我进入内部订阅并使其测试用例看起来不错。
答案 0 :(得分:0)
尝试监视 observableRef
和 component.data
发出,然后调用 fixture.detectChanges()
:
import { of } from 'rxjs';
it("should call testData method", async(() => {
spyOn(observableRef, 'emit').and.returnValue(of("some value"))
spyOn(component.data, 'emit').and.returnValue(of("some value"))
component.testData();
fixture.detectChanges();
expect(component.data.emit).toHaveBeenCalled();
}));