How to test an Angular Resolver

Discussão em 'Angular' iniciado por bob.mazzo, Abril 3, 2025.

  1. bob.mazzo

    bob.mazzo Guest

    I've recently added an Angular "resolver", but now trying to figure out how to write a spec test for it.

    Currently, the test script fails on the 2nd test in app.component.ts with timeout error:

    FAIL app-client-web apps/app-client-web/src/app/app.component.spec.ts (20.929 s)
    AppComponent
    √ should have title 'app-client-web' (170 ms)
    × should create RouterOutlet with valid query parameters (5029 ms)
    √ should have RotuerOutlet be null with invalid query parameter (320 ms)
    ● AppComponent › should create RouterOutlet with valid query parameters
    thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout,
    if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."


    • A sample of our routes (with resolve: { .. }):

      // shell.routes.ts
      import { Routes } from '@angular/router';
      //... (more import here)
      import { globalConfigResolver } from './resolvers/app-config.resolver';

      export const myShellRoutes: Routes = [
      {
      path: 'single',
      component: MyShellComponent,
      canActivate: [myRouteGuard],
      resolve: { appConfig: globalConfigResolver },
      },
      ];


    • Here is "app-config.resolver.ts" :


    import { inject } from '@angular/core';
    import { ResolveFn } from '@angular/router';
    import { myAppSettings } from '@tpnn/my-core';
    import { GlobalConfigLoadService } from '@tpnn/my-data';

    import { catchError, map, of } from 'rxjs';

    // Loads global configuration from server, and maps to front end object.
    export const globalConfigResolver: ResolveFn<MyAppSettings> = route => {
    const configService = inject(GlobalConfigLoadService);
    const orgID = route.queryParams['orgID'];

    return configService.loadGlobalConfigData(orgID).pipe(
    map(config => {
    return configService.mapGlobalConfigToUi(config);
    })
    );
    };

    • app-config.resolver.spec.ts :


    import { TestBed } from '@angular/core/testing';
    import { ResolveFn } from '@angular/router';

    import { globalConfigResolver } from './app-config.resolver';
    import { myAppSettings } from '@tpnn/my-core';

    describe('globalConfigResolverResolver', () => {
    const executeResolver: ResolveFn<myAppSettings > = (...resolverParameters) =>
    TestBed.runInInjectionContext(() => globalConfigResolver(...resolverParameters));

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

    it('should be created', () => {
    expect(executeResolver).toBeTruthy();
    });
    });

    Continue reading...

Compartilhe esta Página