简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM