-1

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
FabianGosebrink
  • 305
  • 2
  • 12
mightycode Newton
  • 3,229
  • 3
  • 28
  • 54

1 Answers1

1

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;
    }
  }
}
AliF50
  • 16,947
  • 1
  • 21
  • 37
  • @AIiF50. Maybe you have a idea to tweak this: https://stackoverflow.com/questions/64386626/how-to-write-unit-test-for-window-location-pathname-with-jasmine-spy. I am really stuck with this – mightycode Newton Oct 16 '20 at 13:32