1

here is my context, angular5 project, ngx-swiper-wrapper library, jasmine and karma. I am writing unit tests for my component but I hava a problem in my unit test:

TypeError: undefined is not an object (evaluating 'this.swiperComponentRef.directiveRef') ngAfterViewInit@http://localhost:8011/_karma_webpack_/main.bundle.js:3642:31382 callProviderLifecycles ...

This is my unit test:

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();
    });
  });
});

And this is my component:

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();
  }
}

It seems that within fixture.detectChanges() when the lifecycle of the component happens, something is not working properly and for some reason the swiperComponentRef is not anymore what it should supposed to be. Any suggestions how to fix the test? Thanks

axel
  • 3,778
  • 4
  • 45
  • 72
  • The swiper component was behind a *ngIf, in the test condition was not passed in order to make the swiper component visible. An exlpanation of the problem is well described here https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined – axel May 05 '18 at 13:40

0 Answers0