How make access to injected ngControl from unit tests?
I solved this by overriding
beforeEach(async () => {
const NG_CONTROL_PROVIDER = {
provide: NgControl,
useClass: class extends NgControl {
control = new FormControl();
viewToModelUpdate() {}
},
};
await TestBed.configureTestingModule({
declarations: [YourComponentName],
imports: [FormsModule],
})
.overrideComponent(YourComponentName, {
add: { providers: [NG_CONTROL_PROVIDER] },
})
.compileComponents();
});
Works with:
beforeEach(() => {
fixture = TestBed.createComponent(сomponent);
(fixture.componentInstance as any).ngControl = new FormControl();
I just had the same issue and solved it using a mock object for the NgControl.
Define the mock object...
let formControlSpy: jasmine.SpyObj<NgControl>;
formControlSpy = jasmine.createSpyObj('NgControl', ['value']);
Provide the mock for component injection...
TestBed.configureTestingModule({
providers: [
TestComponent,
{ provide: NgControl, useValue: formControlSpy }
]
});
injector = getTestBed();
component = injector.get(PasswordFormControlComponent);
Then configure the required value of the control...
beforeEach(() => formControlSpy.value.and.returnValue('value'));