Angular 8 Модульный тест EventSource с использованием Jasmin - PullRequest
1 голос
/ 07 мая 2020

Я использую EventSource в своем приложении и написанную службу-оболочку, как показано ниже:

import { Injectable } from '@angular/core';
import { EventSourcePolyfill } from 'event-source-polyfill';
import { Observable } from 'rxjs';
import { AppConstants } from 'src/app/framework/constants/app.constants';

const base_url = `${AppConstants.REST_API_URL}datacontrolmanagment/notification`;

@Injectable({
  providedIn: 'root'
})
export class SseService {

  private eventSource;
  constructor() { }


  /**
   * 
   * @param url for Event Source Endpoint
   * @param headers passing authorization token
   */
  private getEventSource(headers) {
    return new EventSourcePolyfill(base_url, headers)
  }

  public getServerSentEvents(headers) {
    return Observable.create(observer => {
      if (!(this.eventSource instanceof EventSourcePolyfill)) {
        this.eventSource = this.getEventSource(headers);
      }

      this.eventSource.onmessage = msg => {
        console.log(msg)
        observer.next(msg);
      };

      this.eventSource.onerror = msg => {

      }; 

    });

  };

  public closeEventSource() {
    if ((this.eventSource instanceof EventSourcePolyfill)) {
      this.eventSource.close();
    }
  }
}

Я использовал эту службу в одном из моих компонентов.

Я хочу протестировать эту службу для ради покрытия кода. Однако я не могу понять, как проверить приведенный выше код.

Я попытался создать фиктивный / фиктивный класс EventSource, но не повезло

Примечание: я уже тестировал код компонента для эта услуга.

1 Ответ

0 голосов
/ 07 мая 2020

Поскольку в настоящее время EventSourcePolyfill является внутренней частью SseService, вам вообще не следует издеваться над ним. Вы могли бы издеваться над ним, если бы это была зависимость, переданная, например, конструктором.

У вас есть 2 варианта здесь - создать фабричный токен, который предоставляет EventSourcePolyfill, затем вы можете издеваться над ним.

Или просто закройте, что getServerSentEvents излучает, как EventSourcePolyfill. Не могли бы вы поделиться его кодом в вопросе?

Для первого случая вы можете сделать следующий (это пример, а не рабочая копия)

const base_url = `${AppConstants.REST_API_URL}datacontrolmanagment/notification`;

export const ESP = new InjectionToken<(headers: any) => EventSourcePolyfill>('ESP', {
    factory: () => headers => new EventSourcePolyfill(base_url, headers),
});
@Injectable({
  providedIn: 'root'
})
export class SseService {

  private eventSource;
  constructor(@Inject(ESP) private eventSourceFactory: (headers: any) => EventSourcePolyfill) {}

  public getServerSentEvents(headers) {
    return Observable.create(observer => {
      if (!(this.eventSource instanceof EventSourcePolyfill)) {
        this.eventSource = this.eventSourceFactory(headers);
      }

      this.eventSource.onmessage = msg => {
        console.log(msg)
        observer.next(msg);
      };

      this.eventSource.onerror = msg => {

      }; 

    });

  };

  public closeEventSource() {
    if ((this.eventSource instanceof EventSourcePolyfill)) {
      this.eventSource.close();
    }
  }
}

теперь вы можете издеваться над ним вот так

it('', done => {
  const mockESP: any = jasmine.createSpyObj('EventSourcePolyfill', ['onmessage', 'onerror', 'close']);

  const mockFactory: any = jasmine.createSpy('EventSourceFactory');
  mockFactory.and.returnValue(mockESP);

  const service = new SseService(mockFactory);
  service.getServerSentEvents({myHeaders: true}).subscribe(result => {
    expect(result).toBe('test');
    done();
  });
  mockESP.onmessage.calls.argsFor(0)[0]('test');
  expect(mockESP).toHaveBeenCalledWith({myHeaders: true});
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...