由于ngOnDestroy,无法运行业力测试案例

时间:2017-03-06 06:28:05

标签: angular karma-runner karma-jasmine

我有一个组件作为休闲:

export class InkbarComponent implements AfterViewInit, OnDestroy {
    resizeListener: any;

    constructor(private _renderer: Renderer, private _elementRef: ElementRef, public renderer: Renderer) { }
    ngAfterViewInit() {
        this.resizeListener = this.renderer.listenGlobal('window', 'resize', (event) => {
            if (this.currentElement) {
                this.switchPostion(this.currentElement);
            }
        });
    }
    public switchPostion(element: HTMLElement) {
        // function logic
    }


    ngOnDestroy() {
        this.resizeListener();
    }
}

但当我在其他组件上使用此组件时,karma测试用例开始失败

收到错误:

Error: Error in ./TabContainerComponent class TabContainerComponent - inline template:2:2 caused by: this.resizeListener is not a function
TypeError: this.resizeListener is not a function
    at InkbarComponent.ngOnDestroy (webpack:///src/components/basic-components/ink-bar/inkbar.component.ts:9:4753 <- src/tests.entry.ts:117472:4760)
    at Wrapper_InkbarComponent.ngOnDestroy (/WebBasicModule/InkbarComponent/wrapper.ngfactory.js:13:16)
    at CompiledTemplate.proxyViewClass.View_TabContainerComponent0.destroyInternal (/DynamicTestModule/TabContainerComponent/component.ngfactory.js:342:29)
    at CompiledTemplate.proxyViewClass.AppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12362:0 <- src/tests.entry.ts:23410:19)
    at CompiledTemplate.proxyViewClass.DebugAppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12717:0 <- src/tests.entry.ts:23765:43)
    at CompiledTemplate.proxyViewClass.View_TabContainerComponent_Host0.destroyInternal (/DynamicTestModule/TabContainerComponent/host.ngfactory.js:43:19)
    at CompiledTemplate.proxyViewClass.AppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12362:0 <- src/tests.entry.ts:23410:19)
    at CompiledTemplate.proxyViewClass.DebugAppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12717:0 <- src/tests.entry.ts:23765:43)
    at CompiledTemplate.proxyViewClass.AppView.detachAndDestroy (webpack:///~/@angular/core/bundles/core.umd.js:12346:0 <- src/tests.entry.ts:23394:19)
    at ComponentRef_.destroy (webpack:///~/@angular/core/bundles/core.umd.js:7646:55 <- src/tests.entry.ts:18694:75)

ngOnDestroy

中无法将 resizeListener 作为函数

因此我遇到了很多错误

1 个答案:

答案 0 :(得分:0)

您可以在调用之前检查resizeListener属性是否已定义

或者您可以使用

@HostListener('window:resize', ['$event'])
onWindowResize(event) {
    if (this.currentElement) {
        this.switchPostion(this.currentElement);
    }
}