如何解决 Angular 单元测试用例中的 componentInstance 问题

问题描述 投票:0回答:1

在我用于单元测试的 Angular 18 应用程序中,我只是尝试调用该函数以在规范文件中进行验证。但它不起作用。我正在低于错误。 如何解决这个错误。

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;

}
typescript unit-testing karma-jasmine angular18
1个回答
0
投票

让我们在创建测试模块时声明您的组件

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);
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.