Testing Ionic 2 apps and @ViewChild

Hey everyone,

I’m working on writing unit tests for my ionic 2 app, and I have a @ViewChild call that looks like this:

  <ion-slides #slides (ionSlideDidChange)="onSlideChanged()" pager>

and in my slides.ts I have this:

@ViewChild(Slides) slides: Slides;

This works fine when running the server, and the slides work great, but when I try and write a unit test, slides is undefined. This, of course, breaks everything else.

My unit test setup looks like this:

beforeEach(async(() => TestUtils.beforeEachCompiler([HomePage]).then(compiled => {
  fixture = compiled.fixture;
  component = compiled.instance;

it('should have a defined component', () => {
  // The next line is where it starts throwing the errors.

What can I do to get my @ViewChild defined correctly in a unit test?


Anyone have any ideas? :frowning:

Is there another good place to go to get help on this?

I am facing the same issue here. No success yet.

Apparently unit testing is a new concept for Ionic. Trying to setup a unit test environment is arcane and undocumented (as far as I can tell).

I am having similar issues. I tried a few things, but I can’t seem to get around the errors being thrown at the moment.

As far as I can tell, the issue is that, while the Slides @ViewChild is not undefined when the page is created, it has not loaded properly. I get errors about initEvents of undefined in the swiper-events file.

Ultimately, I’d want to find a way to mock the Slides component as a @ViewChild since I do not want to test Slides functionality, just the code on the actual page. (My E2E tests make sure that the Slides component is working).

Does anyone know how this can be accomplished?

I have no idea how this interacts with @ViewChild, but here’s how to mock subcomponents in general. Define a @Directive with the same selector as the component you wish to mock and give it the same set of @Input properties. Then add this directive to the declarations stanza of your TestBed module configuration.

I’ll give this a try and let you know how it goes.