Is there any way to create mock API for SSE requests in react?

Viewed 45

I have a project that I've implemented mock for all API requests, but somewhere for notification messages, I have SSE requests. I want to know if there is any way to create a mock handler for the SSE API call? Here is the sample code:

useEffect(() => {
    const source = new EventSource(`${baseUrl}/Api/SSE`);
    source.addEventListener("open", (e) => {
      console.log("SSE opened!");
      console.log(e);
    });

    source.addEventListener("message", (e) => {
      console.log(e);
      if (e.data != "null") {
        let temp = JSON.parse(e.data);
        let cashierId = localStorage.getItem("id");
        if (temp.StoreId != cashierId) {
          audio.play().catch((err) => {
            console.log(err);
          });
        }
      }
    });

    source.addEventListener("error", (e) => {
      console.error("Error: ", e);
    });

    return () => {
      source.close();
    };
  }, []);
1 Answers

I'm not sure how to simulate the functionality of the EventSource events. However, to get around the errors from jest you can use:

globals.EventSource = jest.fn(() => undefined)

as a way to suppress the error:

ReferenceError: EventSource is not defined
Related