Test functional route resolver

Discussão em 'Angular' iniciado por ajp11, Setembro 5, 2025.

  1. ajp11

    ajp11 Guest

    Class based route resolvers have been recently deprecated in Angular in favor of functional resolvers. See the documentation here.

    Does anyone have examples of unit testing these functional resolvers?

    I'm not finding any examples in the Angular docs, and the Angular test environment is difficult to configure. So for example, how would one unit test the example function in the docs?

    export const heroResolver: ResolveFn<Hero> =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
    return inject(HeroService).getHero(route.paramMap.get('id')!);
    };


    I'm using a resolver that's basically identical to this in that it calls some service to fetch an entity by ID. When trying to configure call the resolver in Jest, I get the following error:

    NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203

    Continue reading...

Compartilhe esta Página