Search code examples
angulartestingjasminekarma-runner

Angular jasmine toHaveBeenCalledWith with queryParams not working


I have this test:

it('should redurect to admin programs', () => {
    ...

    expect(navigateSpy).toHaveBeenCalledWith(['/admin/programs', {queryParams: {pub_status: 'active'}}]);
});

And its throwing this error:

Error: Expected spy navigate to have been called with 
[ [ '/admin/programs', Object({ queryParams: Object({ pub_status: 'active' }) }) ] ] but actual calls were 
[ [ '/admin/programs' ], Object({ queryParams: [ pub_status: 'active' ] }) ].

Also the activated route mock is like this:

{
  provide: ActivatedRoute,
  useValue: {
    snapshot: {
      queryParams: {
        'countryValId[]': 'ES'
      }
    }
  }
}

And navigate spy is like this:

router = TestBed.get(Router);
navigateSpy = spyOn(router, 'navigate');

How do I solve it? This annotation is very strange:

{ queryParams: [ pub_status: 'active' ] } <-- wtf this is not a proper array

error in terminal

Thanks!!


Solution

  • There are a couple of ways to solve this problem,

    1. Pass flatten parameter in toHaveBeenCalledWith method.

      expect(navigateSpy).toHaveBeenCalledWith(
         ['/admin/programs'], 
         {queryParams: {pub_status: 'active'}}
      );
      
    2. separate out the mostRecent call arguments and verify them one by one. Use toEqual method for object comparision.

       const [routeLink, queryParamsObj] = navigateSpy.calls.mostRecent().args;
       expect(routeLink).toEqual(['/admin/programs']);
       expect(queryParamsObj).toEqual({queryParams: {pub_status: 'active'}});