Jest unit test "Cannot find control with unspecified name attribute"

1.1k Views Asked by At

I'm doing some simple components for my "dynamic-ish" automated form creator and I've just made a component for dropdown:

<div>
  <select [name]="propertyName" [formControl]="customControl" [id]="propertyName">
    <option *ngFor="let option of options" [value]="option.id">
      {{ option.label }}
    </option>
  </select>
</div>

Code is also bare simple:

export class DropdownComponent {
  @Input() public customControl: AbstractControl;
  @Input() public propertyName: string;
  @Input() public options: any[];
}

Now when I run jest to test this component (which test is created by ng cli, so default, I only added ReactiveFormsModule as an import) it fails with the component creation.

  × should create (363 ms)

  ● DropdownComponent › should create

    Cannot find control with unspecified name attribute
      at _throwError (../packages/forms/src/directives/shared.ts:150:9)
      at setUpControl (../packages/forms/src/directives/shared.ts:37:19)
      at ...

Versions:
Angular: 10.1.6
Jest: 26.6.3
Angular CLI: 10.1.7
Node: 14.4.0
OS: win32 x64

1

There are 1 best solutions below

0
On

Since google gave me 10 results (all misleading or impossible), I tried adding/removing parts of the code, came out that customControl needs to be initialized with a value despite it will receive a formcontrol from the outside (as being @Input). This is not a problem with <input> tags but is a problem with <select> tags!

  @Input() public customControl: AbstractControl = new FormControl('');