SpyOn NavController.setRoot() in Ionic 2

Mock out and spyOn NavController.setRoot() in Ionic 2

Posted on March 3, 2017

Tags:

Ionic

Import the NavController module from ionic-angular.

import { NavController } from 'ionic-angular';

Add NavController to the providers array and swap it out for a mock NavController.

providers: [
     { provide: NavController, useValue: mockNavController }
]

Add the mockNavController value.

let mockNavController = {
    setRoot: {

    }
};

Add the spy within the beforeEach().

beforeEach( async( () => {

    spyOn( mockNavController, 'setRoot' ).and.callFake( function () {
        return true;
    });

}));

You can then spy on the setRoot event.

expect( mockNavController.setRoot ).toHaveBeenCalled();