question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

No value accessor for form control when mocking MatSelectModule

See original GitHub issue

Hi,

When trying to mock the mat-select component from Angular Material 9, the following error appears: Error: No value accessor for form control with name: 'toppings'.

The error occurs only when calling fixture.detectChanges() in the test.

Here is a repo with the minimal setup to reproduce this issue: https://github.com/volcomix/ng-mocks-mat-select-issue

<!-- app.component.html -->

<form [formGroup]="pizzaForm">
  <mat-form-field>
    <mat-label>Toppings</mat-label>
    <mat-select formControlName="toppings" multiple>
      <mat-option *ngFor="let topping of toppingList" [value]="topping">{{
        topping
      }}</mat-option>
    </mat-select>
  </mat-form-field>
</form>
// app.component.ts

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  pizzaForm = this.formBuilder.group({
    toppings: [[]],
  });

  toppingList: string[] = [
    'Extra cheese',
    'Mushroom',
    'Onion',
    'Pepperoni',
    'Sausage',
    'Tomato',
  ];

  constructor(private formBuilder: FormBuilder) {}
}
// app.component.spec.ts

import { async, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';
import { MockModule } from 'ng-mocks';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, MockModule(MatSelectModule)],
      declarations: [AppComponent],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    fixture.detectChanges();
    expect(app).toBeTruthy();
  });
});

Error details:

Error: No value accessor for form control with name: 'toppings'
            at _throwError (http://localhost:9876/_karma_webpack_/node_modules/@angular/forms/__ivy_ngcc__/fesm2015/forms.js:3576:1)
            at setUpControl (http://localhost:9876/_karma_webpack_/node_modules/@angular/forms/__ivy_ngcc__/fesm2015/forms.js:3400:1)
            at FormGroupDirective.addControl (http://localhost:9876/_karma_webpack_/node_modules/@angular/forms/__ivy_ngcc__/fesm2015/forms.js:7679:1)
            at FormControlName._setUpControl (http://localhost:9876/_karma_webpack_/node_modules/@angular/forms/__ivy_ngcc__/fesm2015/forms.js:8451:24)
            at FormControlName.ngOnChanges (http://localhost:9876/_karma_webpack_/node_modules/@angular/forms/__ivy_ngcc__/fesm2015/forms.js:8368:1)
            at FormControlName.wrapOnChangesHook_inPreviousChangesStorage (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:26966:1)
            at callHook (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:4730:1)
            at callHooks (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:4690:1)
            at executeInitAndCheckHooks (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:4630:1)

Thank you!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
Volcomixcommented, Jul 10, 2020

For anyone who is experiencing the same issue, here is a workaround by stubbing manually mat-select without ng-mocks:

// app.component.spec.ts

import { Component } from '@angular/core';
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  ReactiveFormsModule,
} from '@angular/forms';
import { async, TestBed } from '@angular/core/testing';
import { MatOptionModule } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MockModule } from 'ng-mocks';
import { AppComponent } from './app.component';

@Component({
  selector: 'mat-select',
  template: '',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: MatSelectStubComponent,
      multi: true,
    },
  ],
})
class MatSelectStubComponent implements ControlValueAccessor {
  writeValue(obj: any) {}
  registerOnChange(fn: any) {}
  registerOnTouched(fn: any) {}
  setDisabledState(isDisabled: boolean) {}
}

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        MockModule(MatFormFieldModule),
        MockModule(MatOptionModule),
      ],
      declarations: [AppComponent, MatSelectStubComponent],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    fixture.detectChanges();
    expect(app).toBeTruthy();
  });
});
0reactions
satanTimecommented, Sep 17, 2021

Hi all dear developers,

This page is quite popular in search results.

Might you create an issue in this repo and describe what you’ve been looking for? Hopefully, your case will be answered.

Read more comments on GitHub >

github_iconTop Results From Across the Web

No value accessor for form control with name... for mat-select ...
I am experiencing problems with mat-select control. when I run the test case, Karma fires me an error saying Error: No value accessor...
Read more >
No value accessor for form control when mocking ... - GitHub
Hi, When trying to mock the mat-select component from Angular Material 9, the following error appears: Error: No value accessor for form ......
Read more >
No Value Accessor Error in Angular Tests - Damir's Corner
Error: No value accessor for form control with unspecified name attribute. The call stack wasn't helpful at all. It included only Angular ...
Read more >
No value accessor for form control - SyntaxFix
I'm using Angular2-rc5, and I'm currently getting an error on my login page. I'm trying to make a form but the console throws...
Read more >
Creating custom form controls in Angular (Control Value ...
This video covers Control Value Accessors, and how we can use them to minimise boilerplate markup in our forms.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found