3

This is the test file

describe('test', () => { 

 let component: myComponent;
 let fixture: ComponentFixture<myComponent>
 let loader: HarnessLoader;

 beforeEach(() => {
   fixture = TestBed.createComponent(myComponent);
   component = fixture.componentInstance;
   fixture.detectChanges();
   loader = TestbedHarnessEnvironment.loader(fixture);
 });

 it('check label', async () => { 
   const form = await loader.getHarness(MatFormFieldHarness); // error line
   const label = await form.hasLabel();
   expect(label).toBeTrue(); 
  }); 
});

This is the HTML

<div class="units-input-container">
  <mat-form-field>
    <mat-label>unit</mat-label>
    <input type="text" required />

  </mat-form-field>
</div>

This is the error I'm getting

Error: Uncaught (in promise): Error: Failed to find element matching one of the following queries:
        (MatFormFieldHarness with host element matching selector: ".mat-form-field")
        Error: Failed to find element matching one of the following queries:
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80

2 Answers2

0

You need to include the Angular Material's modules used in your component, see below:

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        MatFormFieldModule,
        MatInputModule,
        NoopAnimationsModule
      ],
      declarations: [AppComponent]
    })
      .compileComponents();
  });

NOTE: I am assuming you are using a reactive form (ReactiveFormsModule) and that you may use mat-input, that is why I included MatInputModule. NoopAnimationsModule is required for the test to handle the animations.

For more details check the documentation (see documentation).

I created a simple example to experiment with the harness framework. See the test 'mat-form-field should detect errors after validations are triggered' in github.

silver_mx
  • 828
  • 9
  • 16
0

In my case, I had to use form field mdc harness:

import {MatFormFieldHarness} from '@angular/material/mdc-form-field/testing';

which fixed the issue.

Nitin Jadhav
  • 6,495
  • 1
  • 46
  • 48