Karma测试不会创建组件

时间:2017-08-15 18:53:40

标签: javascript angular testing karma-jasmine

我为Angular组件编写了一个简单的测试,用于检查我的组件toBeTruthy()。当我运行它时,我收到错误:' TypeError:无法读取属性' params'在新的SomeComponent中未定义...'

import { AssemblyComponent } from './assembly.component';

describe('SomeComponent', () => {
    let component: AssemblyComponent;

    let mockDynamicTemplateBuilder;
    let mockActivatedRoute;
    let mockINavigationService;
    let mockISiteConfigRetrievalService;

    beforeEach( () => {
        component = new AssemblyComponent (mockDynamicTemplateBuilder, mockActivatedRoute, mockINavigationService, mockISiteConfigRetrievalService);
    });

    describe('create the component', () => {

        it('component should be truthy', () => {

            expect(component).toBeTruthy();
        });
    });
});

组件本身如下所示:

export class AssemblyComponent implements OnDestroy, OnInit {

    // reference for a <div> with #dynamicContentPlaceHolder
    @ViewChild('dynamicContentPlaceHolder', { read: ViewContainerRef })
    protected dynamicComponentTarget: ViewContainerRef;
    // this will be reference to dynamic content - to be able to destroy it
    protected componentRef: ComponentRef<any>;

    private sub: any;
    // until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
    protected wasViewInitialized = false;

    // wee need Dynamic component builder
    constructor(
        protected templateBuilder: DynamicTemplateBuilder,
        private route: ActivatedRoute,
        private navigationService: INavigationService,
        private siteConfigRetrivalService: ISiteConfigRetrievalService
    ) {
        // when there is change, the subscription is invoked
        // based on the current route params
        console.log('break line');
        this.sub = this.route.params.subscribe(params => {
           // fetching page id
            let pageIdLocal = this.navigationService.getPageId();
            let childpage: string = params['childid'];
            if (childpage !== undefined) {
                pageIdLocal = childpage;
            }
            let grandchildpage: string = params['grandchildid'];
            if (grandchildpage !== undefined) {
                pageIdLocal = grandchildpage;
            }
            console.log(' Fetching Page for ' + pageIdLocal);
            // type of device
            let deviceType = this.navigationService.getDeviceType();
            // returns meta data for that page, data coming from that JSON file
            this.siteConfigRetrivalService.getPageConfiguration(pageIdLocal, deviceType).subscribe((data: any) => {
                this.renderDynamicContent(data, deviceType);
            });

        });
    }

    ngOnInit() {
        console.log(' In Assembly OnInit ');
    }
...

似乎我无法测试我的组件(或任何方法)的初始化是因为构造函数体中的逻辑需要在组件初始化之前被模拟。我的理解是你真的不应该在你的构造函数体中有逻辑。像这样的代码甚至可以测试......?我也注意到私有变量,我想这会阻止他们直接测试它们。我该如何处理?

0 个答案:

没有答案