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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…