0

I want to unit test the following guard

resolve(): Observable < Game > {
  return this.gameRoom$.pipe(
    tap(data => {
      this.gameService.updateGame(data);
    }));
}


canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): boolean {
  this.gameRoom$ = this.gameService.fetchGame(next.paramMap.get("gameId")).pipe(shareReplay());
  return this.gameService.isRouteCorrectlyConfigured(state.url);
}

I have setup the following unit tests for CanActivate

  it("it should not activate route", () => {
    const MockSnapshot = {
      url: ""
    } as RouterStateSnapshot;
    expect(guard.canActivate(route.snapshot, MockRouterStateSnapshot)).toBeFalsy();
  });

  it("it should activate route", () => {
    const MockRouterStateSnapshot = {
      url: "/game/someid/some-place"
    } as RouterStateSnapshot;
    expect(guard.canActivate(route.snapshot, MockRouterStateSnapshot)).toBeTruthy();
  });

But how can I unit test the resolve method? I tried it like this, but the observable does not exist since the gameService is not fetching anything. Does it even make sense to test the resolve method? How can I test it?

it("should resolve", () => {
    guard.resolve().subscribe(data => expect(data).toBeTruthy());
  });
JangoCG
  • 823
  • 10
  • 23

1 Answers1

0

I find no meaningful flow inside resolve() so I wouldn't have bother to test it, but technically speaking it is definitely testable.

resolve() has no direct inputs (arguments), however it introduces 2 indirect inputs that should be mocked: gameRoom$ and gameService. Output is an observable (return value) which actually reflects gameRoom$, so you want to verify that values produced by actual observable are identical to the values produced by gameRoom$-mock (tap is not transforming source observable).

So here's a conceptual example (didn't check for compilation) for implementing desired test:


it("should resolve", () => {
  const fakeGame = new Game();
  guard.gameRoom$ = of(fakeGame); // sync-observable
  guard.gameService = { updateGame: (data: any) => ({ }) };
  guard.resolve().subscribe(data => {
    expect(data).toBe(fakeGame);
  });
});
desertech
  • 911
  • 3
  • 7