Testing ActivatedRoute.paramMap without mocking the Router

Viewed 126

I would like to test how a component is handling this.activatedRoute.paramMap in my tests, without mocking the ActivatedRoute (i.e. using the RouterTestingModule, no spies or mocks).

In the following stackblitz,I set up a fairly trivial component listening for the id route parameter:

@Component({ /* ... */})
export class RoutingExamplesComponent {
  constructor(private readonly route: ActivatedRoute, /* ... */) {}

  readonly param$ = this.route.paramMap.pipe(map(params => params.get('id') ?? '<none>'));
  // ...
}

In my tests, I then want to setup my route and ensure the parameter is well propagated:

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [
      RoutingExamplesModule,
      RouterTestingModule.withRoutes([
        {
          path: "route/:id",
          component: RoutingExamplesComponent
        }
      ])
    ]
  });

  fixture = TestBed.createComponent(RoutingExamplesComponent);
  component = fixture.componentInstance;
  router = TestBed.get(Router);
});


it("receives initial setup", async () => {
  fixture.detectChanges();
  await router.navigate(["route", "1234"]);
  fixture.detectChanges();
  expect(fixture.nativeElement.querySelector("p").textContent).toContain(
      "1234"
    );
  });

This test does not pass, as it looks like the parameter is not propagated:

Expected '<none>' to contain '1234'.
Error: Expected '<none>' to contain '1234'. at <Jasmine> at UserContext.eval (https://angular-routing-playground-routing-test.stackblitz.io/~/app/routing-examples/routing-examples.component.spec.ts:31:80)

How can I achieve to get this parameter right, without mocking the router in any way?


Some optional context about what I am doing: most of the stack overflow responses about router testing suggest to mock it, which I believe is a critical mistake to do. I have been successful at testing things against the RouterTestingModule in general, however paramMap is contextual to the sub router.

1 Answers

So I actually found two ways to fix this after a significant amount of investigation.

The route parameter is not provided as the context of the router is the same as the one you have in the component embedding the <router-outlet>. As we are not within the router outlet, we don't have a route bound to the outlet, thus we don't have route parameters propagated.

Solution 1: make it as if you were in the router outlet

This solution basically overrides the ActivatedRoute provider to provide the first child of the router. This uses the same injection mechanism as its definition, but provides the first child of the root context instead of the root context:

TestBed.configureTestingModule({
  imports: [
    RoutingExamplesModule,
    RouterTestingModule.withRoutes([
      // ...
    ])
  ],
  providers: [
    // Patches the activated route to make it as if we were in the
    // <router-outlet>, so we can access the route parameters.
    {
      provide: ActivatedRoute,
      useFactory: (router: Router) => router.routerState.root.firstChild,
      deps: [Router],
    }
  ],
});

Tradeoff: this means the navigation needs to be triggered before the component instantiation, otherwise you will not have the first child of the route defined:

beforeEach(async () => {
  TestBed.configureTestingModule( ... );

  router = TestBed.get(Router);
  await router.navigate(["route", "1234"]);

  fixture = TestBed.createComponent(RoutingExamplesComponent);
});

Solution 2: bootstrap the component in a router outlet

This basically means you instantiate a trivial component simply rendering <router-outlet></router-outlet> and you create this component.

Tradeoff: you no longer have access to the fixture out of the box, you need to retrieve the debug component.

Related