Search code examples
angularunit-testingoauth-2.0jasminekarma-runner

How to unit test a function returning a Promise with then block


I have this code to initialize an authentication using OAuth2 and redirect the user to an authentication server before getting to my application

import {Component} from '@angular/core';
import {JwksValidationHandler, OAuthService} from 'angular-oauth2-oidc';
import {authConfig} from './sso.config';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {

  constructor(private oauthService: OAuthService) {}

  async initAuth(): Promise<any> {
    return new Promise<void>((resolveFn, rejectFn) => {
      this.oauthService.configure(authConfig);
      this.oauthService.tokenValidationHandler = new JwksValidationHandler();
      this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
        if (this.oauthService.hasValidAccessToken()) {   // ----------------> My test can't get in this part
          this.oauthService.setupAutomaticSilentRefresh();
          resolveFn();
        }else {
          this.oauthService.initCodeFlow();
          rejectFn();
        }
      });// --------------------------------> It goes directly here and gives me: SPEC HAS NO EXPECTATIONS
    });
  }

}

I would like to unit test this part using Jasmine and Karma, my test looks like:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  const oauthServiceMock = {
    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }
  };

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [OAuthModule.forRoot(), HttpClientTestingModule],
      providers: [
       {provide: AppComponent, useValue: oauthServiceMock}
      ],
      declarations: [
        AppComponent
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));

  it('Test for initAuth', fakeAsync(() => {

    const spy = spyOn(oauthServiceMock.oauthService, 'loadDiscoveryDocumentAndTryLogin').and.returnValue(Promise.resolve(true));

    component.initAuth().then(() => {
      tick(5000);
      expect(spy).toHaveBeenCalled();

    });

  }));

});

My test can't get into the block then I don't know what am I missing.


Solution

  • I think you're providing the mock function incorrectly.

    Change this:

    const oauthServiceMock = {
        oauthService: {
          loadDiscoveryDocumentAndTryLogin(): Promise<true> {
            return new Promise<true>(resolve => resolve());
          }
        }
      };
    

    To this:

        oauthService: {
          loadDiscoveryDocumentAndTryLogin(): Promise<true> {
            return new Promise<true>(resolve => resolve());
          }
        }
    

    And change this:

    providers: [
           {provide: AppComponent, useValue: oauthServiceMock}
          ],
    

    To this:

    providers: [
           {provide: OAuthService, useValue: oauthServiceMock}
          ],
    

    We need to provide a mock to OAuthService and not AppComponent. That should hopefully resolve your issue.