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