How to unit test OidcSecurityService.Auth() with jasmine?

1.3k views Asked by At

I am using Jasmine for unit testing. And I am using OidcSecurityService. So I made a mock for it, like this:

export class OidcSecurityServiceStub{
  getToken(){
     return 'some_token_eVbnasdQ324';
  }
}

and I have this component:

export class AutoLoginComponent implements OnInit {
  lang: any;

  constructor(public oidcSecurityService: OidcSecurityService) {}

  /**
   * responsible that user will be redirected to login screen.
   */
  ngOnInit() {
      this.oidcSecurityService.checkAuth().subscribe(() => this.oidcSecurityService.authorize());
  }

}

and this how the spec looks like now:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AutoLoginComponent ],
      providers:    [ {provide: OidcSecurityService, useClass: OidcSecurityServiceStub} ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AutoLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create autologin component ',  () => {

    const fixture  = TestBed.createComponent(AutoLoginComponent);
    expect(component).toBeTruthy();
  });
});

But I get this error:

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

So what I have to change?

Thank you

So I made this change:

import { AuthOptions } from 'angular-auth-oidc-client/lib/login/auth-options';
import { of } from 'rxjs';

export class OidcSecurityServiceStub {
  getToken() {
    return 'some_token_eVbnasdQ324';
  }

  checkAuth(url: string) {
    return of(url);
  }

  authorize(authOptions?: AuthOptions){
    return authOptions.urlHandler('http://localhost');
  }
}

but then I get this error:

AfterAll TypeError: Cannot read property 'urlHandler' of undefined
1

There are 1 answers

1
AliF50 On BEST ANSWER

In your ngOnInit, you are calling authorize without any arguments and when it calls authorize of your stub, it is undefined.

You can try changing the mock to something like this:

import { AuthOptions } from 'angular-auth-oidc-client/lib/login/auth-options';
import { of } from 'rxjs';

export class OidcSecurityServiceStub {
  getToken() {
    return 'some_token_eVbnasdQ324';
  }

  checkAuth(url: string) {
    return of(url);
  }

  authorize(authOptions?: AuthOptions){
    if (authOptions) {
      return authOptions.urlHandler('http://localhost');
    } else {
      return null;
    }
  }
}