Angular Karma Jasmine TypeError: Cannot read properties of undefined (reading 'controls') at UserContext.apply app.componet.spec.ts

56 views Asked by At

When I run the test I get the error TypeError: Cannot read properties of undefined (reading 'controls').

Why I can't access controls in my test file?

My function:

loadData() {
 if (this.rootForm.get(['name'])?.value &&
        this.rootForm.get(['address'])?.value) {
        this.signatureflag = true;
 }else {
  this.signatureflag = false
 }
 
 }

it('load data ',() =>{
     let fixture: ComponentFixture<ImportantMattersComponent>;
     fixture = TestBed.createComponent(ImportantMattersComponent);
     fixture.componentInstance.rootForm.controls.name.setValue('name');
     fixture.componentInstance.rootForm.controls.address.setValue('address');
     component.loadData();
});
3

There are 3 answers

0
Rの卄IT On BEST ANSWER

In your test cases SPEC HAS NO EXPECTATIONS should not load data when form fields are empty

it('load data ', () => {
    component.rootForm.controls.name.setValue('name');
    component.rootForm.controls.address.setValue('address');
    component.loadData();
    expect(component.signatureflag).toBe(true);
  });

  it('should not load data when form fields are empty', () => {
    component.rootForm.controls.name.setValue('');
    component.rootForm.controls.address.setValue('');
    component.loadData();
    expect(component.signatureflag).toBe(false);
  });

Working Example - Stackblitz

2
Naren Murali On

Could you try running fixture.detectChanges() before accessing the form properties

Documentation reference for fixture.detectChanges()

it('load data ',() =>{
     let fixture: ComponentFixture<ImportantMattersComponent>;
     fixture = TestBed.createComponent(ImportantMattersComponent);
     component = fixture.componentInstance;
     fixture.detectChanges(); // <- changed here!
     component.rootForm.controls.name.setValue('name');
     component.rootForm.controls.address.setValue('address');
     component.loadData();
});

Usually we place the first three lines in a beforeEach block and then the remaining code runs in the it block, else you will repeat the same lines for each test case!

0
Vaibhavi Parmar On

It is because of your form object fixture.componentInstance.rootForm is null while you are setting value to controls. So Make sure your form object should be set with controls with blank values. for ex:

 rootForm = new FormGroup({
    name: new FormControl(''),
    address: new FormControl('')
  });

Either you can try this: add ? after rootForm.

      fixture.componentInstance.rootForm?.controls.name.setValue('name');
      fixture.componentInstance.rootForm?.controls.address.setValue('address');

Or put this 2 lines in settimeout function:

    setTimeout(()=>{                     
        fixture.componentInstance.rootForm.controls.name.setValue('name');
          fixture.componentInstance.rootForm.controls.address.setValue('address');
});