我正在尝试测试数据与模板之间的角度绑定。问题是对mat chip的引用返回空值。
下面是我要测试的组件模板:
<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回购:
https://github.com/capozzic1/bookshelf
此外,这是一种在现实发展世界中会发生的测试吗?这是一个很好的实践,还是有不同的方法?