如何对在angular7中具有@Input变量的组件进行单元测试?

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

我有一个angular组件,其中有一些Input()变量,这些变量来自像这样的parent组件

componet.ts

  @Input() transactions: any[] = [];
  @Input() total: number = 0;
  @Input() cash: number = 0;
  @Input() card: number = 0;
  @Input() cheque: number = 0;


  ngOnInit() {
   this.paidToDate = (this.card || 0) + (this.cash || 0) + (this.cheque || 0);
  }

并且当我尝试对此组件进行单元测试时,该组件只有这样的组件creation的基本单元测试

component.spec.ts

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

 beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ 
    EstimateTotalComponent
  ],
  imports: [
    FormsModule,
    CheckboxModule,
    DropdownModule,
    TableModule,
    AutoCompleteModule,
    HttpClientModule,
    SharedModule,
    RouterTestingModule,
    CookieModule.forRoot(),
    ToastrModule.forRoot(),
    NgxMaskModule.forRoot(),
    TabViewModule,
    LoadingBarHttpClientModule,
    BrowserAnimationsModule
  ],
  providers: [
    HTTPService,
    HelperService,
    DateService,
    ValidationService,
    CookieService,
    ToastrService,
    SocketService,
    CalculationService,
    DataService,
    DialogService
   ],
   schemas : [ CUSTOM_ELEMENTS_SCHEMA]
 })
  .compileComponents();
}));

 beforeEach(() => {
  fixture = TestBed.createComponent(EstimateTotalComponent);
  component = fixture.componentInstance;
  component.transactions = [];
  component.total = 0;
  component.cash = 0;
  component.card = 0;
  component.cheque = 0;
  fixture.detectChanges();
});

it(UNIT_TEST.ComponentCreated, () => {
 expect(component).toBeTruthy();
});

但是它会抛出这样的错误。

如何摆脱这个错误?

enter image description here

angular typescript karma-jasmine
1个回答
0
投票

@Inpu中定义所有beforeEach t变量

beforeEach(() => {
  fixture = TestBed.createComponent(EstimateTotalComponent);
  component = fixture.componentInstance;
  component.total=0;
  component.cash = 0;
  component.card = 0;
  component.cheque = 0;
  fixture.detectChanges();
});
© www.soinside.com 2019 - 2024. All rights reserved.