ismaestro
ismaestro

Reputation: 8267

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!!

Upvotes: 1

Views: 2115

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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

Upvotes: 2

Fateh Mohamed
Fateh Mohamed

Reputation: 21377

this is the syntax of Router navigate method, you have an error in array brackets []

this.router.navigate(['/admin/programs'], {queryParams: {pub_status: 'active'}});

and not

this.router.navigate(['/admin/programs', {queryParams: {pub_status: 'active'}}]);

so it has to be

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

Upvotes: 0

Related Questions