Search code examples
angularionic-frameworkkarma-jasmineangular-test

Angular Jasmine test case for navigation and getCurrentNavigation not working


My component has both getCurrentNavigation and router.navigate

I have implemented getCurrentNavigation from here

Now page having

constructor() {
 if (router.getCurrentNavigation().extras.state) {
      this.levelId = router.getCurrentNavigation().extras.state.arcadeSelectedGame;
    }
}

and navigation to another page

const navigationExtras: NavigationExtras = {
        state: {
          dummyObject,
          gameplay_log_data,
          arcadeLevelData: this.arcadeLevelData
        }
      };
 this.router.navigate(['ad-page'], navigationExtras)

Now I have applied solution from here then navigation works but then router.getCurrentNavigation().extras.state stopped working


Solution

  • I found a value to implement both the cases parallels. I have defined navigate: jasmine.createSpy('navigate') with getCurrentNavigation. and used useValue in provide in place of useClass.

    Here is the code.

    let mockRouter = {
        navigate: jasmine.createSpy('navigate'),
        getCurrentNavigation: () => {
          return {
             extras: {
                state:{
                  arcadeSelectedGame: '-LAbVp7C0lTu9CV-Mgt-'
                }
              }
            }
          }
      }
    

    In Provider array

    { provide: Router, useValue: mockRouter},

    let router: Router;
    

    Inside foreach

    router = TestBed.inject(Router);
    

    Test cases

    it('Play click check navigation', async () => {
       component.playArcade();
       expect(mockRouter.navigate).toHaveBeenCalledTimes(1)
       expect(mockRouter.navigate).toHaveBeenCalledWith(['ad-page']);
    })