Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

angular - Testing ActivatedRoute.paramMap without mocking the Router

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.

question from:https://stackoverflow.com/questions/65902273/testing-activatedroute-parammap-without-mocking-the-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...