How to mock ngControl in Custom Form Control - Unit tests Angular

Viewed 2661

I'm looking for some example with unit tests for Custom Form Control in Angular 9. That part constructor(@Self() private ngControl: NgControl) causes an error: Error: NodeInjector: NOT_FOUND [NgControl]. Since I need to set value accessor somehow.

I'm injecting ngControl in constructor since I need to use ngControl later in my component. That's why I didn't use typical implementation with provide: NG_VALUE_ACCESSOR.

I was trying to mock it by:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        providers: [
            { provide: NgControl, useValue: new FormControlDirective([], [], [], null) }
        ],
        imports: [FormsModule, ReactiveFormsModule]
    }).compileComponents();

But I have an error: No valid value accessor for form control with unspecified name attribute since I don't know what should be under 3rd parameter of function FormControlDirective which is: valueAccessors: ControlValueAccessor[]

Does anyone have idea how can I mock this?

2 Answers

Try mocking it like so:

let mockNgControl: any;

beforeEach(async(() => {
    mockNgControl = jasmine.createSpyObj('ngControl', ['value', /* mock other methods required here */]);
    TestBed.configureTestingModule({
        providers: [
            { provide: NgControl, useValue: mockNgControl }
        ],
        imports: [FormsModule, ReactiveFormsModule]
    }).compileComponents();

The problem was because I didn't import my Module with CustomFormControl in Imports array. That's why it didn't work. Maybe it will help someone.

Related