Как провести модульный тест OidcSecurityService.Auth() с жасмином?

Я использую Jasmine для модульного тестирования. И я использую OidcSecurityService. Поэтому я сделал макет для него, например:

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

и у меня есть этот компонент:

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

}

и вот как сейчас выглядит спецификация:

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

Но я получаю эту ошибку:

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

Так что я должен изменить?

Спасибо

Поэтому я сделал это изменение:

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

но затем я получаю эту ошибку:

AfterAll TypeError: Cannot read property 'urlHandler' of undefined

person mightycode Newton    schedule 14.10.2020    source источник


Ответы (1)


В вашем ngOnInit вы вызываете authorize без каких-либо аргументов, и когда он вызывает authorize вашей заглушки, он не определен.

Вы можете попробовать изменить макет на что-то вроде этого:

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;
    }
  }
}
person AliF50    schedule 14.10.2020
comment
@AIiF50. Возможно, у вас есть идея изменить это: stackoverflow.com/questions/64386626/. я действительно застрял с этим - person mightycode Newton; 16.10.2020