Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' ] ].
like image 880
suchip Avatar asked Jan 21 '26 02:01

suchip


1 Answers

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

like image 111
Xesenix Avatar answered Jan 22 '26 20:01

Xesenix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!