title: how to mock EventSource using jest with TS (tried most of the mocking strategy)
body: <p>wanted to mock EventSource using jest, but kept throwing <code>ReferenceError: EventSource is not defined</code>.</p>
  
  <p>Please have a look at the code. Thanks a lot!</p>
  
  <pre><code>// eventSourceHandler.ts
  export default new class A() {
  listenEventSource(){
      const eventSource = new EventSource(url);
      eventSource.addEventListener("something", callSomething);
      eventSource.onerror = function() {
        console.error();
        ("Failed to listen EventSource");
      };
  }
  }
  </code></pre>
  
  <p>Here is test code I want to mock </p>
  
  <pre><code>// eventSourceHandler.spec.ts
  
  import A from "./eventSourceHandler"
  describe("xyz",() =&gt;{
  it("eventSourceHandler called", ()=&gt; {
  const mEventSourceInstance = {
          addEventListener: jest.fn(),
          onerror: jest.fn(),
          close: jest.fn(),
          onmessage: jest.fn(),
          onopen: jest.fn(),
          url: "test-url",
          readyState: 0,
          withCredentials: false,
          CLOSED: 2,
          CONNECTING: 0,
          OPEN: 1,
          removeEventListener: jest.fn(),
          dispatchEvent: jest.fn()
        };
        jest.mock("EventSource", () =&gt; {
          return {
            EventSource: jest.fn().mockImplementation(() =&gt; {
              return {
                // addEventListener: jest.fn(),
                // onerror: jest.fn()
                mEventSourceInstance
              };
            })
          };
        });
        let a = new A()
        a.listenEventSource();
        // test validation ....
  });
  });
  });
  ...
  
  </code></pre>
  
  <p>Kept getting <code>ReferenceError: EventSource is not defined</code> whenever run test code.</p>
  
  <p><strong>NOTE:</strong> I've read almost most related posts from stackoverflow and tried to mock <code>global.EventSource</code> but Typescript kept throwing error saying <code>EventSource does not exist on type Global</code>.</p>
  
  <p>Is there anyone who wants to share a better mocking strategy for this?
  That will be highly appreciated.</p>
  
  <p>Thanks guyzz ...</p>