suchip
suchip

Reputation: 137

How to match partial url in toHaveBeenCalledWith in Angular

I'm testing the url by matching some part of it by using toHaveBeenCalledWith and the parameter should be without null/.

expect(router.navigate).toHaveBeenCalledWith(jasmine.objectContaining(['/home'])); 

After I tried the command above, I got this error:

Expected spy navigate to have been called with [ <jasmine.objectContaining([ '/home' ])> ] but actual calls were [ [ 'null/home' ] ].

Upvotes: 3

Views: 893

Answers (1)

Xesenix
Xesenix

Reputation: 2548

You need setup your testing with either RouterTestingModule but that would require from you testing result of navigation instead of checking navigate arguments used.

Instead, you can have something like this:

class RouterMock {
  navigate = jasmine.createSpy('navigate')
}

TestBed.configureTestingModule({
  providers: [
    {
      provide: Router,
      useClass: RouterMock 
    },
    ...
  ]
});

You can check spy last called arguments something like this:

it('should...', inject([Router], (router: RouterMock) => {
  // ... setup test
  expect(router.navigate.calls.mostRecent().args).toEqual(jasmine.objectContaining(['/home'])); 
}))

Stackblitz example

Upvotes: 2

Related Questions