代码之家  ›  专栏  ›  技术社区  ›  Dream_Cap

为什么在我的集成测试中不能参考角材料的mat芯片?

  •  0
  • Dream_Cap  · 技术社区  · 6 年前

    我正在尝试测试数据与模板之间的角度绑定。问题是对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

    此外,这是一种在现实发展世界中会发生的测试吗?这是一个很好的实践,还是有不同的方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rex Bloom    6 年前

    移动这条线

    component.book = dummyBook;
    

    在查询选择器行上方。您的mat-chip元素周围有一个*ngif,在将mat-chip添加到dom之前,需要在组件上设置一本书。