Как смоделировать подписку Angular в тесте Жасмин - PullRequest
0 голосов
/ 04 февраля 2020

Я пытаюсь исправить юнит-тест (я не особенно знаком с Жасмин) после добавления некоторых подписок на сервис. Я получаю сообщение о том, что они не определены. Я не уверен, как правильно включить подписки.

Мой компонент (это еще не все, но я сократил для ясности):

export class AppComponent implements OnInit, AfterViewInit {
  isSignedIn = false;
  isLoggedIn = false;
  signedInSubscription: Subscription;
  loggedInSubscription: Subscription;

  constructor(
    private authenticationService: AuthenticationService,
    private router: Router,
    private http403Tester: Http403TestService,
  ) {
    this.isLoggedIn = authenticationService.isLoggedIn;
    this.isSignedIn = authenticationService.isSignedIn;
    this.setEnvironment();
  }

  async ngOnInit() {
    // line 69 below, this is where the error is
    this.signedInSubscription = this.authenticationService.observableIsSignedIn.subscribe(item => {
      this.isSignedIn = item;
    });
    this.loggedInSubscription = this.authenticationService.observableIsLoggedIn.subscribe(item => {
      this.isLoggedIn = item;
    });
  }  
}

Служба:

export class AuthenticationService {
  constructor() {
    this.observableIsSignedIn = new BehaviorSubject<boolean>(this.isSignedIn);
    this.observableIsLoggedIn = new BehaviorSubject<boolean>(this.isLoggedIn);
  }

  isSignedIn: boolean = null;
  isLoggedIn: boolean = null;
  observableIsSignedIn: any;
  observableIsLoggedIn: any;

spe c:

describe('AppComponent', () => {
  let authenticationService: any;
  let http403Tester: any;
  let router: any;
  let component: AppComponent;

beforeEach(() => {
  authenticationService = {
    isSignedIn: jasmine.createSpy(),
    isLoggedIn: jasmine.createSpy(),
    observableIsSignedIn: jasmine.createSpy(),
    observableIsLoggedIn: jasmine.createSpy(),
  };
  router = { navigateByUrl: jasmine.createSpy() };
  http403Tester = { isAuthenticated: jasmine.createSpy() };
  component = new AppComponent(authenticationService, router, http403Tester);
});

describe('ngOnInit()', () => {
  it('should navigate to /unauthorised when a 403 status code is returned', async () => {
  // Arrange
  http403Tester.isAuthenticated.and.returnValue(false);

  // Act
  await component.ngOnInit();

  // Assert
  expect(router.navigateByUrl).toHaveBeenCalledWith('/unauthorised');
});

И ошибка:

TypeError: Cannot read property 'subscribe' of undefined
at AppComponent.<anonymous> (src/app/app.component.ts:69:83)

Так что я почти уверен, что createSpy () - неправильный способ макет подписки:

observableIsSignedIn: jasmine.createSpy()

Но я понятия не имею, как поступить или что искать. Есть идеи?

1 Ответ

0 голосов
/ 04 февраля 2020

Попробуйте это

 authenticationService = {
    isSignedIn: jasmine.createSpy(),
    isLoggedIn: jasmine.createSpy(),
    observableIsSignedIn: new BehaviorSubject<boolean>(undefined).asObservable(),
    observableIsLoggedIn:  new BehaviorSubject<boolean>(undefined).asObservable(),
  };

Для более подробной информации: Пересмешивание объекта поведения в тестовом компоненте spe c

Обновление:

На самом деле вы пропустили правильную конфигурацию для модульного тестирования. пожалуйста, проверьте: https://angular.io/guide/testing#component -дом-тестирование

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...