Поскольку в настоящее время 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});
}