Angular Test Spec For @okta/okta-angular V 6

I have a pretty simple component that gets an OktaAuthStateService, for observing the authState, and a OktaAuth, for signing in & out, and I want to write a test spec for them that gives me full code coverage. Only problem is with the 2 objects that are injected into the constructor.

import { Component, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { OktaAuthStateService, OKTA_AUTH } from '@okta/okta-angular';
import OktaAuth, { AuthState } from '@okta/okta-auth-js';
import { filter, map, Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public isAuthenticated$!: Observable<boolean>;
  public name$!: Observable<string>;

  constructor(private _router: Router,
    private _oktaStateService: OktaAuthStateService,
    @Inject(OKTA_AUTH) private _oktaAuth: OktaAuth)
  {

  }


  public ngOnInit(): void {
    this.isAuthenticated$ = this._oktaStateService.authState$.pipe(
      filter((s: AuthState) => !!s),
      map((s: AuthState) => s.isAuthenticated ?? false)
    );
    this.name$ = this._oktaStateService.authState$.pipe(
      filter((authState: AuthState) => !!authState && !!authState.isAuthenticated),
      map((authState: AuthState) => authState.idToken?.claims.name ?? '')
    );
  }

  public async signIn() : Promise<void> {
    await this._oktaAuth.signInWithRedirect().then(
      _ => this._router.navigate([''])
    );
  }

  public async signOut(): Promise<void> {
    await this._oktaAuth.signOut();
  }
}

What should my test spec look like?

Would this help?

This uses jest and does not have all the injectables that I need. Also the project does not reference the @okta/angular-sdk b/c it is the sdk.

If this component had a corresponding test spec that would be fantastic

okta-angular/protected.component.ts at master · okta/okta-angular (github.com)

Hi there @bUb!

When setting up the test bed, you’ll want to add all types injected into the component in your providers array. So in your example, you’ll add OktaAuthStateService and OktaAuth, and import the RouterTestingModule.

Here’s an example of how to do so and mock both services using Karma:

2 Likes