如何在Angular中匹配toHaveBeenCalledWith中的部分url

时间:2019-08-15 10:01:34

标签: angular unit-testing jasmine

我正在通过使用toHaveBeenCalledWith匹配URL的一部分来测试URL,并且该参数应该不包含null/

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

尝试上面的命令后,出现此错误:

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

1 个答案:

答案 0 :(得分:0)

您需要使用RouterTestingModule来设置测试,但这需要您测试导航的结果,而不是检查使用的导航参数。

相反,您可以有这样的内容:

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

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

您可以检查间谍最后调用的参数,如下所示:

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

Stackblitz example