Why can't I get a reference to Angular Material's mat-chip in my integration test?

I am trying to test the binding of data to my template in Angular. The problem is that the reference to mat-chip returns null.

Here is the template for my component that I'm trying to test:

<mat-card fxLayout="column" fxLayoutAlign="center center" class="book-card">
        <img [src]="book?.bookCover?.thumbnail" alt="book cover">
    <mat-card-content>

        <mat-chip-list *ngIf="book.category" class="chip-group">

                <mat-chip>{{book.category[0]}}</mat-chip>
            </mat-chip-list>
    </mat-card-content>

    <mat-card-header>
        <mat-card-title>{{ book?.title | truncate }}</mat-card-title>
        <mat-card-subtitle><p>by {{ book?.author ? book?.author[0] : "No author" }}</p></mat-card-subtitle>
    </mat-card-header>
</mat-card>

Here is my test:

import { By } from '@angular/platform-browser';
import { MatChipsModule } from '@angular/material/chips';
import { Book } from './../book';
import { BookComponent } from './book.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TruncatePipe } from '../pipes/truncate.pipe';
import { MatCardModule } from '@angular/material/card';

describe('BookComponent', () => {
    let component: BookComponent;
    let fixture: ComponentFixture<BookComponent>;

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [MatChipsModule, MatCardModule],
        declarations: [BookComponent, TruncatePipe],
        //schemas: [NO_ERRORS_SCHEMA],

    });
    fixture = TestBed.createComponent(BookComponent);
    component = fixture.componentInstance;
});

    it('should render the category, author, and title in the template', () => {
        const dummyBook = new Book('chocolate', ['food'], ['Dart'], 'test.jpg', 2);
        //this line doesn't seem to reference the element
        let element = fixture.nativeElement.querySelector('mat-chip');

        component.book = dummyBook;
        fixture.detectChanges();

        //returns null, why?
        console.log(element);
        //expect(element).toContain('Dart');
    });
});

Here is the git repo: https://github.com/capozzic1/bookshelf

Also, is this a type of test that would occur in the real world of development? Is this a good practice to get into or is there a different way?

1 answer

  • answered 2018-08-14 22:01 Rex Bloom

    Move this line

    component.book = dummyBook;
    

    above your query selector line. You have an *ngIf around your mat-chip element that will require a book to be set on the component before the mat-chip will be added to the DOM.