Home > Back-end >  Getting cannot read properties of undefined (reading:'viewMode') in Angular Unit Testing
Getting cannot read properties of undefined (reading:'viewMode') in Angular Unit Testing

Time:11-02

Hi I have a function which I would like to unit test. This is my function.

let docProcess: IDocProcess;

public onCalling(args) {
    if (this.docProcess.viewMode) {
      this.makeCalls(args);
    }
}

This IDocProcess is an interface:

export interface IDocProcess {
  viewMode: boolean;
  editMode: boolean;
  deleteMode: boolean;
}

I would like to unit test the above function. If I pass docProcess.viewMode as true, makeCalls(args) function should be called. If false, then the function must not be called.

The following is my Unit test code:


 beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [CallsComponent],
      providers: [
        MockData
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));


  beforeEach(() => {
    fixture = TestBed.createComponent(CallsComponent);
    component = fixture.componentInstance;
  });


  it('should call makeCalls() only on View Mode', () => {
    
    component.docProcess.viewMode = true;
    fixture.detectChanges();
    component.onCalling(mockArgsData);    
    expect(component.makeCalls).toHaveBeenCalled();

But the test results get failed. Getting cannot read properties of undefined (reading:'viewMode').

Is this because the Testing module couldn't recognize the interface. A similar situation like this, I am also getting "Cannot set properties of undefined (setting: variable_name)"

Please help me in resolving this.

CodePudding user response:

I think you can try with component.docProcess = {viewMode = true}; because since the property is not initialized you need to create the object instead of trying to asign one property to undefined

CodePudding user response:

Angular generally throws such errors while testing to check if that variable exists or not. Mostly writing that code inside if(variable_name) {--code giving undefied variable_name error---}

resolves the issue , as we are checking in our ts code that variable_name is not undefined.

  • Related