这是我的上下文,angular5项目,ngx-swiper-wrapper库,jasmine和karma。 我正在为我的组件编写单元测试但是我的单元测试存在问题:
TypeError:undefined不是对象(评估' this.swiperComponentRef.directiveRef') ngAfterViewInit @ http://localhost:8011/_karma_webpack_/main.bundle.js:3642:31382 callProviderLifecycles ...
这是我的单元测试:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ExperienceModalComponent } from './experience.modal';
import { SwiperModule, SWIPER_CONFIG, SwiperComponent, SwiperDirective } from 'ngx-swiper-wrapper';
import { DEFAULT_SWIPER_CONFIG } from '../../../config/swiper';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [SwiperModule],
declarations: [MyComponent],
providers: [
{ provide: SWIPER_CONFIG, useValue: DEFAULT_SWIPER_CONFIG }
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component.swiperComponentRef = <any>{
directiveRef: {
update: jasmine.createSpy('update'),
nextSlide: jasmine.createSpy('nextSlide')
}
};
fixture.detectChanges();
});
describe('#constructor', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
});
});
这是我的组件:
import { Component, Input, ViewChild, AfterViewInit } from '@angular/core';
import { SwiperComponent, SwiperConfigInterface } from 'ngx-swiper-wrapper';
@Component({
selector: 'app-my-content',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements AfterViewInit {
public swiperConfig: SwiperConfigInterface = {
keyboard: false,
mousewheel: false,
scrollbar: false,
navigation: false,
pagination: false,
autoplay: false
};
@ViewChild(SwiperComponent) swiperComponentRef: SwiperComponent;
constructor() {
}
ngAfterViewInit(): void {
this.swiperComponentRef.directiveRef.update();
}
}
似乎在fixture.detectChanges()内部,当组件的生命周期发生时,某些东西无法正常工作,并且由于某种原因,swiperComponentRef不再是它应该是什么。 有什么建议如何修复测试?感谢