import SseSource from "~/services/sse/sseSource";
import {EventSourcePolyfill} from "event-source-polyfill";

class TestableSseSource extends SseSource {
  public eventSource: EventSourcePolyfill | null = null
  public createEventSource(url: string, withCredentials: boolean): EventSourcePolyfill {
    return super.createEventSource(url, withCredentials)
  }
}

describe('SseSource', () => {
  describe('createEventSource', () => {
    it('returnValidEventSourcePolyfill', () => {
      const sseSource = new TestableSseSource(
        'http://mercure',
        '',
        () => {},
        (eventData) => {},
        () => {}
      )

      const eventSource = sseSource.createEventSource('http://mercure', true)

      expect(eventSource.url).toEqual('http://mercure')
      expect(eventSource.withCredentials).toEqual(true)
    })
  })

  describe('isConnected', () => {
    it('is true when readyState is open', () =>
    {
      const eventSource = new EventSourcePolyfill('http://mercure')
      Object.defineProperty(eventSource, 'readyState', {value: EventSourcePolyfill.OPEN})

      const sseSource = new TestableSseSource(
        'http://mercure',
        '',
        () => {},
        (eventData) => {},
        () => {}
      )

      sseSource.eventSource = eventSource
      expect(sseSource.isConnected()).toBeTruthy()
    })
    it('is false else', () => {
      const sseSource = new TestableSseSource(
        'http://mercure',
        '',
        () => {},
        (eventData) => {},
        () => {}
      )
      expect(sseSource.isConnected()).toBeFalsy()
    })
  })
})
