How make access to injected ngControl from unit tests? How resolve the error?
In component
constructor(
@Self() @Optional() public ngControl: NgControl
) { }
ngOnInit(): void {
this.ngControl.valueChanges
In unit test
beforeEach(() => {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
When executing the test get the error
TypeError: Cannot read property 'valueChanges' of null
Works with:
beforeEach(() => {
fixture = TestBed.createComponent(сomponent);
(fixture.componentInstance as any).ngControl = new FormControl();
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();
});
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With