Angular 单元测试不适用于扩展基类的类

Angular 单元测试不适用于扩展基类的类,angular,jasmine,Angular,Jasmine,我正在努力测试一个扩展了另一个抽象类的组件类 这两个类别如下: export abstract class BaseListComponent { constructor( protected someImportantService: SomeImportantService ){ } handleListInitialization() { // Do lots of things this.doOtherS

我正在努力测试一个扩展了另一个抽象类的组件类

这两个类别如下:

export abstract class BaseListComponent {
    constructor(
        protected someImportantService: SomeImportantService
    ){

    }

    handleListInitialization() {
        // Do lots of things
        this.doOtherStuff();
    }

    /**
     * @abstract doOtherStuff Function
     */
    protected abstract doOtherStuff( );
}


export class MyListComponent extends BaseListComponent {
    constructor(
        someImportantService: SomeImportantService,
        private listService: ListService
    ) {
        super( someImportantService );
    }

    doStuff = () => {
        this.handleListInitialization();
    }

    doOtherStuff(){
        this.listService.getThings().then(() => {
            // process response...
         })
    }
}
我试图测试在
MyListComponent
中调用
doStuff
时,它将导致在
doOtherStuff
方法中调用
listService.getThings()

describe('When calling doStuff()', () => {
        it('should call getThings from the ListService instance', (  ) => {
            spyOn(component.listService, 'getThings').and.returnValue(Promise.then({foo: 'bar'}));
            component.doStuff();
            expect(component.listService.getThings).toHaveBeenCalled();
        });
    });
执行此测试时,我收到一个错误,说从未调用过spy,但奇怪的是,我的覆盖率报告显示了我的
doOtherStuff()
实现的所有行

如果我在测试套件中调用
doOtherStuff()
,那么测试通过得很好

我不明白为什么会发生这种情况,我想知道我的抽象基类是否以某种方式被错误地实现了,尽管在运行应用程序时,一切都如我所期望的那样工作


这里可能有什么问题?

您需要发布更多代码,说明如何创建
组件,可能是模拟的,在这种情况下,预期会失败。这些类及其继承看起来不错,在所描述的情况下应该通过测试。

问题在于调用
doOtherStuff
时,就在您订阅/参与承诺的那一刻

如果要接收this.listService.getThings()的值,需要等待下一个时钟执行

为了处理这个问题,你可以使用和的角度

我认为我们可以用fakeAsync重写您的测试,如下所示:

describe('When calling doStuff()',() => {
        it('should call getThings from the ListService instance',  fakeAsync(() => {
            component.doStuff();
            tick();
            fixture.detectChanges();
            spyOn(component.listService, 'getThings').and.returnValue(Promise.then({foo: 'bar'}));
            tick();
            fixture.detectChanges();
            expect(component.listService.getThings).toHaveBeenCalled();
        }));
});
应该是这样的