簡體   English   中英

如何使用 jest 和 TS 模擬 EventSource(嘗試了大部分模擬策略)

[英]how to mock EventSource using jest with TS (tried most of the mocking strategy)

想用玩笑模擬 EventSource,但一直拋出ReferenceError: EventSource is not defined

請看一下代碼。 非常感謝!

// 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");
    };
}
}

這是我想模擬的測試代碼

// eventSourceHandler.spec.ts

import A from "./eventSourceHandler"
describe("xyz",() =>{
it("eventSourceHandler called", ()=> {
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", () => {
        return {
          EventSource: jest.fn().mockImplementation(() => {
            return {
              // addEventListener: jest.fn(),
              // onerror: jest.fn()
              mEventSourceInstance
            };
          })
        };
      });
      let a = new A()
      a.listenEventSource();
      // test validation ....
});
});
});
...

每次運行測試代碼時,都會收到ReferenceError: EventSource is not defined

注意:我已經閱讀了來自 stackoverflow 的幾乎大多數相關帖子,並嘗試模擬global.EventSource但 Typescript 不斷拋出錯誤,說EventSource does not exist on type Global

有沒有人想為此分享更好的嘲笑策略? 這將受到高度贊賞。

謝謝蓋茲...

好吧,我看到了您可能會使用的兩種替代方法。

  • 在它正在使用的類中注入 eventSource 實例,這樣你就可以模擬它
  • 使用builder函數而不是直接在A類中調用構造函數

對於后者,你可能會得到這樣的結果:

utils.ts

export const buildEventSource = (url: string) => {
  return new EventSource(url, {});
};

然后在您的測試類中:

import * as utils from './utils';

const buildEventSourceSpy = jest.spyOn(utils, 'buildEventSource');

buildEventSourceSpy.mockReturnValue({
    CLOSED: 0,
    CONNECTING: 0,
    OPEN: 0,
    dispatchEvent(event: Event): boolean {
      return false;
    },
    onerror: jest.fn(),
    onmessage: jest.fn(),
    onopen: jest.fn(),
    readyState: 0,
    url: '',
    withCredentials: false,
    addEventListener(
      type: any,
      listener: any,
      options?: boolean | AddEventListenerOptions
    ): void {},
    close(): void {},
    removeEventListener(
      type: any,
      listener: any,
      options?: boolean | EventListenerOptions
    ): void {}
  });

我希望它有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM