我试图在Angular中测试数据到模板的绑定。问题是对mat-chip的引用返回null。
这是我要测试的组件模板:
<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>
这是我的考试:
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');
});
});
这是git repo:https://github.com/capozzic1/bookshelf
这也是在现实的开发世界中会发生的一种测试吗?这是进入的好习惯还是有其他方法?
答案 0 :(得分:1)
移动此行
component.book = dummyBook;
在查询选择器行上方。您在垫芯片元素周围有一个* ngIf,这要求在将垫芯片添加到DOM之前在组件上设置一本书。