Goutm
Goutm

Reputation: 33

How to resolve componentInstance issue in angular unit test case

In my angular 18 application for the unit test, Just i am trying to call the function to veify in the spec file. But It is not working. I am getting below the error. How to resolve this error.

TypeError: Cannot read properties of undefined (reading 'componentInstance')

app.component.spec.ts:

import {
  TestBed,
  ComponentFixture
} from '@angular/core/testing';
import { provideMockStore } from '@ngrx/store/testing';
import { MyInputComponent } from './my-input.component';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

describe('MyInputComponent', () => {
  let component: MyInputComponent;
  let fixture: ComponentFixture<MyInputComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      providers: [ReactiveFormsModule, provideMockStore()],
    }).compileComponents();
  });

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


  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call addNumber', () => {
    component.addNumber(); //Getting componentInstance Error 
    expect(component.addNumber).toHaveBeenCalled();
  });

});

app.component.ts:

addNumber(){

let a = 5;
let b = 19;
return a+b;

}

Upvotes: 0

Views: 40

Answers (2)

4strodev
4strodev

Reputation: 1

Based on the angular documentation, the only difference that I could see is that on the docs, they use waitForAsync instead of declaring directly an asynchronous function when configuring the testModule.

Upvotes: 0

hoangdv
hoangdv

Reputation: 16147

Let's declare your component when creating the testing module

describe('MyInputComponent', () => {
  let component: MyInputComponent;
  let fixture: ComponentFixture<MyInputComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyInputComponent], // Declare the component
      providers: [ReactiveFormsModule, provideMockStore()],
    }).compileComponents();
    fixture = TestBed.createComponent(MyInputComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });


  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call addNumber', () => {
    expect(component.addNumber()).toEqual(24);
  });
});

Upvotes: 0

Related Questions