Angular 如何在toHaveBeenCalledWith中匹配部分url
我正在测试url,通过使用Angular 如何在toHaveBeenCalledWith中匹配部分url,angular,unit-testing,jasmine,Angular,Unit Testing,Jasmine,我正在测试url,通过使用toHaveBeenCalledWith匹配url的某些部分,参数应该不带null/ expect(router.navigate).toHaveBeenCalledWith(jasmine.objectContaining(['/home'])); 在我尝试上面的命令后,出现以下错误: Expected spy navigate to have been called with [ <jasmine.objectContaining([ '/home' ])
toHaveBeenCalledWith
匹配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' ] ].
预期spy navigate已被[]调用,但实际调用为[['null/home']。
您需要使用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']));
}))
您可以检查spy上次调用的参数,如下所示:
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']));
}))
我不能使用mostRecentCall。为什么它应该是spy?你是如何监视这种方法的?或者你使用的间谍路由器类型不正确,我使用的是间谍(路由器“导航”);如果我使用expect(router.navigate),它工作得很好
jasmine.objectContaining
用于toEqual
而不是toHaveBeenCalledWith
如果你想与间谍一起使用它,你需要参考mostRecentCall
或通过间谍机制添加的其他参数。我是否可以使用toHaveBeenCalledWith的其他命令来验证url?