Wie teste ich OidcSecurityService.Auth () mit Jasmin?

Oct 14 2020

Ich benutze Jasmine für Unit-Tests. Und ich benutze OidcSecurityService. Also habe ich mich so lustig gemacht:

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

und ich habe diese Komponente:

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());
  }

}

und so sieht die Spezifikation jetzt aus:

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();
  });
});

Aber ich bekomme diesen Fehler:

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

Also was muss ich ändern?

Vielen Dank

Also habe ich diese Änderung vorgenommen:

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');
  }
}

aber dann bekomme ich diesen Fehler:

AfterAll TypeError: Cannot read property 'urlHandler' of undefined

Antworten

1 AliF50 Oct 15 2020 at 06:26

In Ihrem ngOnInitAufruf rufen Sie authorizeohne Argumente auf, und wenn es authorizeIhren Stub aufruft , ist es undefiniert.

Sie können versuchen, das Modell in etwa so zu ändern:

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;
    }
  }
}