Error: mat-form-field must contain a MatFormFieldControl

Viewed 465

I am currently looking deeper at some of the warnings I am getting in my Jasmine/Karma tests and when I tried adding the MatFormFieldModule and MatInputModule as follows:

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();
  });
});

My test case is giving me the error message in the title of the post on this of html, I know this because when I comment this block out the error goes away.

<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>

Based on a post I found on stackoverflow I changed the input tag to this

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

But even after doing that I am still the same error. Is there something else I am missing?

1 Answers

It may be related to another angular material component that you are using in your application. Import MatSelectModule worked for me.

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

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