Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make access to injected ngControl from unit tests?

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

like image 600
Vitaliy.Makogon Avatar asked Jul 31 '18 16:07

Vitaliy.Makogon


3 Answers

Works with:

beforeEach(() => {
     fixture = TestBed.createComponent(сomponent);
     (fixture.componentInstance as any).ngControl = new FormControl();
like image 64
Vitaliy.Makogon Avatar answered Nov 03 '22 11:11

Vitaliy.Makogon


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();
  });
like image 21
vijay kumar Avatar answered Nov 03 '22 11:11

vijay kumar


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'));
like image 3
Ben Wesson Avatar answered Nov 03 '22 09:11

Ben Wesson