【问题标题】:Error: mat-form-field must contain a MatFormFieldControl错误:mat-form-field 必须包含 MatFormFieldControl
【发布时间】:2021-01-30 07:40:17
【问题描述】:

我目前正在深入研究我在 Jasmine/Karma 测试中遇到的一些警告,当我尝试如下添加 MatFormFieldModule 和 MatInputModule 时:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialogRef, MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserApiService } from 'src/app/services/api/user-apiservice';
import { InitService } from 'src/app/services/tops/initializer.service';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'

import { AddUserComponent } from './adduser.component';

describe('AddUserComponent', () => {
  let component: AddUserComponent;
  let fixture: ComponentFixture<AddUserComponent>;
  let mockMatDialogRef, mockTlsApiService, mockInitService, mockMatDialog, mockMatSnackBar, mockMAT_DIALOG_DATA;

  beforeEach(async(() => {
    mockInitService = jasmine.createSpyObj(['Roles']);

    TestBed.configureTestingModule({
      declarations: [ AddUserComponent ],
      providers: [
        {provide: MatDialogRef, useValue: mockMatDialogRef},
        {provide: UserApiService, useValue: mockTlsApiService},
        {provide: InitService, useValue: mockInitService},
        {provide: MatDialog, useValue: mockMatDialog},
        {provide: MatSnackBar, useValue: mockMatSnackBar}
      ],
      imports: [
        MatFormFieldModule, MatInputModule
      ]
    })
    .compileComponents();
  }));

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

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

我的测试用例在这个 html 的帖子标题中给了我错误消息,我知道这一点,因为当我评论这个块时,错误消失了。

<mat-form-field appearance="fill">
  <mat-label>Search for Either: First Name and/or Last Name, or ID</mat-label>
  <input matInput (keyup)="search($event.target.value)" placeholder="Search for Either: First Name and/or Last Name, or ID">
</mat-form-field>

根据我在 stackoverflow 上找到的帖子,我将输入标签更改为这个

<input matInput (keyup)="search($event.target.value)" placeholder="Search for Either: First Name and/or Last Name, or ID" />

但即使这样做了,我仍然是同样的错误。我还有什么遗漏的吗?

【问题讨论】:

标签: angular typescript jasmine karma-jasmine


【解决方案1】:

它可能与您在应用程序中使用的另一个角度材料组件有关。 Import MatSelectModule 对我有用。

import { MatSelectModule } from '@angular/material/select';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ YourComponent ],
    imports: [ 
      ...,
      MatSelectModule 
    ]
  })
  .compileComponents();
});

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2019-05-29
    相关资源
    最近更新 更多