Search code examples
unit-testingangularionic2angular2-testing

How to mock NavParams in tests?


This might be an Ionic 2 only question, as I don't see NavParams in the Angular 2 docs, but some concepts might translate so I tagged both.

Given that I call navparams.get('somekey') in order to listen to parameters that are passed in, it's tricky to mock the NavParams in tests.

For example, here's how I currently do it:

export class NavParamsMock {
  public get(key): any {
    return String(key) + 'Output';
  }
}

This works for really basic tests, but what if I had a component that I have to test that it gets a specific type of Object, eg a User.

Then, I can do something like

export class NavParamsMock {
  public get(key): any {
    if (key === 'user') {
       return new User({'name':'Bob'})
    }
    return String(key) + 'Output';
  }
}

But, this doesn't work if you want to use the get(user) in another test, or even another component's spec. Say you use NavParams in 2 different components, and they both expect different result when you do get(user), it becomes increasingly tricky to mock.

Has anyone found a solution to this scenario?


Solution

  • You can get value of your choice by implementing your own setter method.

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

    Then in each test you can access the service and set your own params object.

    beforeEach(() => {
      NavParamsMock.setParams(ownParams); //set your own params here
      TestBed.configureTestingModule({
        providers: [
          {provide: NavParams, useClass: NavParamsMock},
        ]
      });
    })