Search code examples
angularangular2-testing

Angular 2 testing


I have a component. Hes main role to be wrapper.

In what trouble?

When method compileComponents executing the component has no property title. Thats why, as i think, in console i see error enter image description here

Question is: How i can first bind property and then run compileComponents method?

Component template:

<div class="card">
    <div *ngIf="title" class="card-header clearfix">
        <h3 class="card-title">{{ title }}</h3>
    </div>
    <div class="card-body">
        <ng-content></ng-content>
    </div>
</div>

Describe section:

describe('CardComponent', () => {

    let comp: CardComponent;
    let fixture: ComponentFixture<CardComponent>;
    let titleEl: DebugElement;  // the DebugElement with the welcome message

    // async beforeEach
    beforeEach( async(() => {
        TestBed.configureTestingModule({
            declarations: [ CardComponent ],
        }).compileComponents(); // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() => {
        fixture = TestBed.createComponent(CardComponent);
        comp    = fixture.componentInstance;
        titleEl = fixture.debugElement.query(By.css('.card-title'));

        comp.title   = "Greatest title";
        fixture.detectChanges(); // trigger initial data binding
    });

    it('Card check title', () => {
        expect(titleEl.nativeElement.textContent).toContain("Greatest title");
    });
});

Solution

  • It's because you are trying to get the element before it even exists. The title determines *ngIf the element is visible. Just move trying to get the element to after you detect changes

    beforeEach(() => {
      fixture = TestBed.createComponent(CardComponent);
      comp = fixture.componentInstance;
      // titleEl = fixture.debugElement.query(By.css('.card-title'));
    
      comp.title = 'Greatest title';
      fixture.detectChanges(); // trigger initial data binding
      titleEl = fixture.debugElement.query(By.css('.card-title'));
    });