Angular 用于导航和 getCurrentNavigation 的 Jasmine 测试用例不工作

Angular Jasmine test case for navigation and getCurrentNavigation not working

我的组件有 getCurrentNavigationrouter.navigate

我已经从

实现了 getCurrentNavigation

现在页面有

constructor() {
 if (router.getCurrentNavigation().extras.state) {
      this.levelId = router.getCurrentNavigation().extras.state.arcadeSelectedGame;
    }
}

并导航到另一个页面

const navigationExtras: NavigationExtras = {
        state: {
          dummyObject,
          gameplay_log_data,
          arcadeLevelData: this.arcadeLevelData
        }
      };
 this.router.navigate(['ad-page'], navigationExtras)

现在我应用了 的解决方案,然后导航可以正常工作,但 router.getCurrentNavigation().extras.state 停止工作

我找到了一个可以同时实现这两种情况的值。 我用 getCurrentNavigation 定义了 navigate: jasmine.createSpy('navigate')。并使用 useValue 代替 useClass.

这是代码。

let mockRouter = {
    navigate: jasmine.createSpy('navigate'),
    getCurrentNavigation: () => {
      return {
         extras: {
            state:{
              arcadeSelectedGame: '-LAbVp7C0lTu9CV-Mgt-'
            }
          }
        }
      }
  }

在提供者数组中

{ provide: Router, useValue: mockRouter},

let router: Router;

foreach 内部

router = TestBed.inject(Router);

测试用例

it('Play click check navigation', async () => {
   component.playArcade();
   expect(mockRouter.navigate).toHaveBeenCalledTimes(1)
   expect(mockRouter.navigate).toHaveBeenCalledWith(['ad-page']);
})