在我用于单元测试的 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;
}
让我们在创建测试模块时声明您的组件
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);
});
});