No value accessor for form control with name... for mat-select controls

xze*_*gga 3 unit-testing karma-jasmine angular-material angular

I am making some unit test with jasmine and karma for an angular 6 app that validate if a formGroup field is valid. I am experiencing problems with mat-select control. when I run the test case, Karma fires me an error saying Error: No value accessor for form control with name: 'importId'. By the way, the component works fine as I expected.

在此处输入图片说明

This is my component:

import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
  modelForm: FormGroup;
  imps;
constructor(
    public dialogRef: MatDialogRef<MyComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {
      this.imps = data['imp'];
  }


  ngOnInit() {
    this.modelForm = new FormGroup({
      name: new FormControl(null, Validators.required),
      importId: new FormControl(null, Validators.required),
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

My HTML template looks like this:

<mat-dialog-content>
  <form [formGroup]="modelForm">

    <mat-form-field>
      <input matInput
             placeholder="Name"
             formControlName="name">
    </mat-form-field>

    <mat-form-field>
      <mat-select placeholder="Source import"
                  formControlName="importId">
        <mat-option *ngFor="let imp of imps" [value]="imp.uuid">
          {{imp.label}}
        </mat-option>
      </mat-select>
    </mat-form-field>

  </form>
</mat-dialog-content>

<mat-dialog-actions>
  <button mat-raised-button color="primary" [disabled]="!modelForm.valid" (click)="someFakeFunction()">Create</button>
  <button mat-raised-button (click)="dialogRef.close()">Cancel</button>
</mat-dialog-actions>
Run Code Online (Sandbox Code Playgroud)

Finally, this is my unit test:

import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {MockMatDialogData, MockMatDialogRef} from '@testing/mock/material';
import {MyComponent} from './evaluation-wizard.component';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {NO_ERRORS_SCHEMA} from "@angular/core";


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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [ReactiveFormsModule, FormsModule],
      providers: [
        {provide: MatDialogRef, useValue: MockMatDialogRef},
        {provide: MAT_DIALOG_DATA, useClass: MockMatDialogData}
      ],
      schemas: [NO_ERRORS_SCHEMA],
    })
      .compileComponents();
  }));

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

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

  describe('Form validation', () => {
    it('form invalid when empty ', function () {
      expect(component.modelForm.valid).toBeFalsy();
    });

    it('name field validity ', () => {
      let name = component.modelForm.controls['name'];
      expect(name.valid).toBeFalsy();

      let errors = {};
      errors = name.errors || {};
      expect(errors['required']).toBeTruthy();

      name.setValue("test");
      errors = name.errors || {};
      expect(errors['required']).toBeTruthy();
    });

  });
});
Run Code Online (Sandbox Code Playgroud)

我无法使它正常工作,我缺少什么建议?

小智 12

就我而言,我忘记了

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

在模块中。

所以如果你导入它应该可以工作。


JB *_*zet 5

您不会在测试模块中导入材料模块。

因此mat-form-fieldmat-select等等仅被Angular视为未知元素(因为您通过使用告诉它这样做NO_ERRORS_SCHEMA)。


Jan*_*ler 5

我认为您缺少一些重要的模块,这就是 Angular 编译器不知道这些模块的原因。在您的导入中至少添加以下内容(我猜还有更多内容):

imports: [ReactiveFormsModule, FormsModule,
  BrowserModule,
  BrowserAnimationsModule,
  MatSelectModule,
  MatOptionModule,
  MatInputModule
],
Run Code Online (Sandbox Code Playgroud)

也使用

schemas: [CUSTOM_ELEMENTS_SCHEMA],
Run Code Online (Sandbox Code Playgroud)

告诉编译器能够检测非 HTML 标签。

通过该修复,您将不需要NO_ERRORS_SCHEMA, 在这些简单的情况下不应使用它。