【问题标题】:Unit test not behaving for a class that extends a base class单元测试不适用于扩展基类的类
【发布时间】:2020-04-26 07:11:00
【问题描述】:

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

两个类如下:

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();
        });
    });

执行此测试时,我收到一条错误消息,指出从未调用过间谍,但奇怪的是,我的覆盖率报告显示我的 doOtherStuff() 实现的行已完全覆盖。

如果我在我的测试套件中调用doOtherStuff(),那么测试通过就好了。

我不明白为什么会发生这种情况,我想知道我的抽象基类是否以某种方式错误地实现了,尽管在运行应用程序时一切正常。

这可能是什么问题?

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    问题是当doOtherStuff 被调用时,就在那一刻你正在订阅/参与 Promise。

    如果你想收到this.listService.getThings() 的值,你需要等到下一个时钟被执行。

    要处理这个问题,您可以使用 Angular 的 fakeAysnctick

    我认为我们可以像这样使用 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();
            }));
    });
    

    它应该可以工作。

    【讨论】:

      【解决方案2】:

      您需要发布更多如何创建component 的代码,也许它被嘲笑了,在这种情况下,失败是意料之中的。类和它们的继承看起来不错,应该在所描述的情况下通过测试。

      【讨论】:

        猜你喜欢
        • 2012-03-14
        • 2012-11-14
        • 2020-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-15
        • 2020-01-01
        • 2016-12-19
        相关资源
        最近更新 更多