Angular jasmine toHaveBeenCalledWith 与 queryParams 不工作

Angular jasmine toHaveBeenCalledWith with queryParams not working

我有这个测试:

it('should redurect to admin programs', () => {
    ...

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

它抛出这个错误:

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' ] }) ].

激活的路由模拟也是这样的:

{
  provide: ActivatedRoute,
  useValue: {
    snapshot: {
      queryParams: {
        'countryValId[]': 'ES'
      }
    }
  }
}

导航间谍是这样的:

router = TestBed.get(Router);
navigateSpy = spyOn(router, 'navigate');

如何解决?这个注解很奇怪:

{ queryParams: [ pub_status: 'active' ] } <-- wtf this is not a proper array

谢谢!!

这是路由器导航方法的语法,你在数组括号中有错误[]

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

而不是

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

所以它必须是

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

有几种方法可以解决这个问题,

  1. 在 toHaveBeenCalledWith 方法中传递 flatten 参数。

    expect(navigateSpy).toHaveBeenCalledWith(
       ['/admin/programs'], 
       {queryParams: {pub_status: 'active'}}
    );
    
  2. 将最近的调用参数分离出来,一一验证。使用 toEqual 方法进行对象比较。

     const [routeLink, queryParamsObj] = navigateSpy.calls.mostRecent().args;
     expect(routeLink).toEqual(['/admin/programs']);
     expect(queryParamsObj).toEqual({queryParams: {pub_status: 'active'}});