如何使用ActivatedRoute的多个父路由对组件进行单元测试

时间:2017-08-18 14:04:50

标签: angular unit-testing typescript karma-jasmine

假设我有一个访问父路线的组件,如下所示:

ngOnInit() {
    //TODO - FFBZAP-25: far from an ideal solution
    this.sub = this.route.parent.parent.parent.params.subscribe(params => {
        this.siteId = params["siteId"];
        this.loadContents();
        this.loadTypes(this.siteId);
    });
}

我的问题是,当我运行测试时,我得到了

  

失败:无法读取属性' undefined'未定义的

我现在没有测试路线,但我认为错误应该是因为这一行:

  • useValue:{parent:{parent:{parent:{' params&#39 ;: Observable.from([{' siteId':' 156'}]) },},

这是我的单元测试代码:

beforeEach(async(() => {

    TestBed.configureTestingModule({
        imports: [
            HttpModule,
            RouterTestingModule,
            SharedModule,
            BootstrapModalModule
        ],
        declarations: [
            ContentListComponent,
        ],
        providers: [
            SiteService,
            UserService,
            Modal,
            Overlay,
            {
                provide: ActivatedRoute,
                useValue: { parent: { parent: { parent: { 'params': Observable.from([{ 'siteId': '156' }]) } } } },
            },
            OverlayRenderer,
            AuthHttp,
            MessageService,
        ],
        schemas: [NO_ERRORS_SCHEMA]

    }).compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(ContentListComponent);
            component = fixture.componentInstance;
            siteService = TestBed.get(SiteService);
            userService = TestBed.get(UserService);
            activatedRoute = TestBed.get(ActivatedRoute);

        });
}));
console.log("HEUUUYFYYHSIDDHARTHs", { parent: { parent: { parent: { 'params': Observable.from([{ 'siteId': '11' }]) } } } })
it('should have a defined component', () => {
    expect(component).toBeDefined();
});
it('Sholud get content-list', async(() => {

    spyOn(userService, 'getUser')
        .and.returnValue(Observable.of(UpdatedBy));

    spyOn(siteService, 'getSiteContents')
        .and.returnValue(Observable.of(contentList));
    fixture.detectChanges();
    component = new ContentListComponent(activatedRoute, mockModal, mockRouter, siteService, userService);
    component.ngOnInit();


    fixture.whenStable()
        .then(() => {
            fixture.detectChanges();
            return fixture.whenStable();
        })
        .then(() => {
            const totalRows = de.queryAll(By.css('tr'));
            expect(totalRows.length).toEqual(3);
        });
}));
});

我试图参考以下链接。但我现在可以得到满意的结果 How to mock an activatedRoute parent Route

Testing Angular 2 parent route

0 个答案:

没有答案