vendredi 28 octobre 2016

Testing an Angular 2 component with async-populated child components

I am trying to write tests for a compound component, populated with an observable, but as this is one of the first Angular2 tests I am writing.

I have a component named ListContainerComponent which is populated using Observable list$ with children instances of ListItemComponent.

ListContainerComponent's template follows:

<list-item
    *ngFor="let listItem of (list$ | async)" [item]="listItem"></list-item>

Works great in the browser. The tests however break on that the [item] is allegedly not a known property of ListItemComponent which is not exactly true, as it does have @Input() item in it.

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { ListContainerComponent } from './list-container.component';
import { Store, StoreModule } from '@ngrx/store';

import * as fromRoot from '../../../reducers';
import { Observable } from 'rxjs';
import { reducer } from '../../../reducers/list.reducer';

describe('Component: ListContainer', () => {
    let storeStub;
    let component: ListContainerComponent;
    let fixture: ComponentFixture<ListContainerComponent>;
    let element: HTMLElement;

    beforeEach(() => {
        storeStub = {
            items: []
        };

        TestBed.configureTestingModule({
            declarations: [
                ListContainerComponent
            ],
            providers: [
                {provide: Store, useValue: storeStub}
            ],
            imports: [
                StoreModule.provideStore(reducer),
            ]
        })
        .compileComponents();

        fixture = TestBed.createComponent(ListContainerComponent);
        component = fixture.componentInstance;
        element = fixture.nativeElement;
    });

    it('should populate list', async(() => {
        component.list$ = Observable.of([
            {name: 'abc', value: 'content of abc'},
        ]};

        fixture.detectChanges();
        expect(element.querySelectorAll('h4').length).toBeGreaterThan(0);

    }));
});

Sorry I am not providing a working plunker, but I don't know yet how to create tests in plunker. I believe the mistaking I am making is an obvious one, probably showing my wrong approach, and easy to spot by those in the know.

Aucun commentaire:

Enregistrer un commentaire