Mocking out NavParams in Ionic 2 unit tests

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

Posted on March 3, 2017

Tags:

Ionic

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