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.