'Angular tests with OktaAuthModule: Having RouterTestingModule throws NullInjectorError: No provider for Router

I'm trying to run tests (Nx/Jest) with my component that uses Okta (v3).

I have a guard that extends from OktaAuthGuard with this code:

@Injectable()
export class AuthGuard extends OktaAuthGuard {}

With this spec:

describe("AuthGuard", () => {
  TestBed.resetTestEnvironment();
  TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, OktaAuthModule],
      providers: [
        AuthGuard,
        { provide: AuthRepository, useClass: AuthMockRepository },
        PROVIDE_OKTA_CONFIG,
        OktaAuthService,
        OktaAuthGuard,
      ],
    });
  });

  it("service injected", inject([AuthGuard], (guard: AuthGuard) => {
    expect(guard).toBeTruthy();
  }));
});

When I run the tests I get this error even when I have RouterTestingModule imported.

 FAIL   project apps/paceart/src/app/presentation/guards/auth.guard.spec.ts (6.13 s)
  AuthGuard
    × service injected (297 ms)

  ● AuthGuard › service injected

    NullInjectorError: R3InjectorError(DynamicTestModule)[AuthGuard -> Router -> Router]:
      NullInjectorError: No provider for Router!

As it can be seen, I tried adding the OktaAuthModule to imports section, OktaAuthGuard and OktaAuthService to providers section. Also I tried adding the okta dependency as a peerDependency, and then the router dependency too.

  "peerDependencies": {
    "@okta/okta-angular": "3.2.2",
    "@angular/router": "13.3.6"
  }

What can I have to do to make this work?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source