首页 > 解决方案 > 使用幻灯片进行离子单元测试会引发 TypeError

问题描述

我有一个引用我的组件,ion-slides它在组件初始化期间引发错误:

<ion-content class="blue-purple-gradient" [fullscreen]="true">
  <ion-slides pager="true" #slides>
    ...
  </ion-slide>
</ion-slides>

export class ReEvaluationComponent implements OnInit, OnDestroy, AfterViewInit {
  @ViewChild(IonSlides, {static: false}) slides: IonSlides;

  ...

  ngAfterViewInit() {
    if (this.slides) {
      this.slides.lockSwipeToNext(true)
    }
  }
}

这在运行测试时会引发以下错误:

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

这是测试:

describe('ReEvaluationComponent', () => {

  beforeEach(async(() => {
    NavParamsMock.setParams({
      client: {dob: "1991-01-22"}
    })
    TestBed.configureTestingModule({
      declarations: [ ReEvaluationComponent ],
      imports: [
        IonicModule.forRoot(),
        HttpClientTestingModule,
        RouterTestingModule,
        FormsModule,
        SharedModule,
        ReactiveFormsModule
      ],
      providers: [
        {provide: Storage, useValue: storageMock},
        {provide: NavParams, useValue: navParams},
        {provide: WeighInsProvider, useValue: weighInsServiceMock},
        {provide: GlobalsService, useValue: mockGlobalsService},
        {provide: TransactionsProvider, useValue: transactionsServiceMock},
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    injector = getTestBed()
    checkInsService = injector.get(CheckInsProvider)
    weighInsService = injector.get(WeighInsProvider)
    transactionsService = injector.get(TransactionsProvider)
  })

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

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

标签: angularunit-testingionic-framework

解决方案


Ion-slides 将在下一个 ionic 版本中被弃用,所以与其尝试像你正在做的那样实现它,我建议迁移到将成为我们下一个 'ion-slide' 的 Swiper 并且不会给你带来那么多麻烦。

如果您想了解更多信息:

https://ionicframework.com/docs/api/slides#migration

您可以查看此视频解释使用:

https://www.youtube.com/watch?v=XcvieKvmI5A

或者按照这个教程:

https://ionicacademy.com/swiper-with-ionic/


推荐阅读