Mocking out NavParams in Ionic 2 unit tests

Solving the "Failed: Can't resolve all parameters for NavParams: (?)" error

Posted on March 3, 2017

Import the NavParams module.

import { NavParams } from 'ionic-angular';

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

TestBed.configureTestingModule( {
    providers: [
        { provide: NavParams, useClass: NavParamsMock },
    ],
} ).compileComponents();

Add the NavParamsMock class.

class NavParamsMock {
    static returnParam = null;
    public get(key): any {
        if (NavParamsMock.returnParam) {
            return NavParamsMock.returnParam
        }
        return 'default';
    }
    static setParams(value){
        NavParamsMock.returnParam = value;
    }
}
  • Property data missing

  • CJ Coffey

    this worked for me

    class NavParamsMock {
    static returnParam = undefined;
    get data() { return NavParamsMock.returnParam; }
    set data(params) { NavParamsMock.returnParam = params; }
    public get(key): any {
    if (NavParamsMock.returnParam && NavParamsMock.returnParam[key]) {
    return NavParamsMock.returnParam[key];
    }
    return ”;
    }
    static setParams(value) {
    NavParamsMock.returnParam = value;
    }
    }

    // … in the .spec file

    beforeEach(() => {
    fixture = TestBed.createComponent(MyPage);
    comp = fixture.componentInstance;
    comp.navParams.data = { name: ‘bill’ };
    });