Jasmine&Karma:在测试Angular时,“ mat-chip-list”不是一个已知元素

时间:2019-04-08 11:42:59

标签: html angular jasmine karma-runner

当我尝试使用Jasmine和Karma运行测试时出现此错误:

'mat-chip-list' is not a known element:
1. If 'mat-chip-list' is an Angular component, then verify that it is part of this module.
2. If 'mat-chip-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("iv class="tag">IAM</div>
    <mat-form-field class="chips" (focusout)="saveFormValue('iam')">
      [ERROR ->]<mat-chip-list #chipListIAM class="field">
        <mat-chip *ngFor="let iam of iams"
               "): ng:///DynamicTestModule/Component.html@33:6

问题是当我运行Angular代码时,我没有遇到这样的问题,因为我在AppModule中声明了我的元素,所以一切都无法正确运行,所以我不知道为什么在测试时会出现此错误。

这是我的HTML代码:

  <div class="left-side">
    <mat-form-field class="chips" (focusout)="saveFormValue('groups')">
      <mat-chip-list #chipListGroup class="field">
        <mat-chip *ngFor="let group of groups"
                  [selectable]="selectable"
                  [removable]="removable"
                  [color]="primary"
                  selected
                  (removed)="onRemoveGroup(group)">
          {{group.name}}
          <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
        </mat-chip>
      </mat-chip-list>
    </mat-form-field>
  </div>

这是我的AppModule:

@NgModule({
  declarations: [Component, DetailsComponent],
  exports: [
    Component
  ],
  imports: [
    CommonModule,
    MatChipsModule,
    MatFormFieldModule,
    MatInputModule,
    BrowserAnimationsModule,
    MatIconModule,
    MatSelectModule,
    FormsModule
  ]
})

这是我的测试文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { FormRoutesDetailsComponent } from './details.component';
import { FormsModule } from '@angular/forms';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DetailsComponent ],
      imports: [
        FormsModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

1 个答案:

答案 0 :(得分:0)

您还必须在TestingModule中导入MatChipsModule(以及要测试的组件使用的所有其他模块)。

TestBed.configureTestingModule({
  declarations: [ DetailsComponent ],
  imports: [
    FormsModule,
    MatChipsModule
  ]
})