gpt4 book ai didi

typescript - 如何使用 jest 和 TS 来模拟 EventSource(尝试了大部分模拟策略)

转载 作者:行者123 更新时间:2023-12-03 08:47:32 27 4
gpt4 key购买 nike

想要使用 Jest 来模拟 EventSource,但一直抛出 ReferenceError:EventSource 未定义

请看一下代码。非常感谢!

// 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未定义

注意:我已经阅读了 stackoverflow 上几乎大多数相关的帖子,并尝试模拟 global.EventSource 但 Typescript 一直抛出错误,说 EventSource 不存在于输入全局

有没有人想为此分享更好的模拟策略?我们将不胜感激。

谢谢guyzz...

最佳答案

嗯,我看到您可能会使用两种替代方案。

  • 将 eventSource 实例注入(inject)正在使用的类中,以便您可以模拟它
  • 使用构建器函数而不是直接在类 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 {}
});

希望对你有帮助

关于typescript - 如何使用 jest 和 TS 来模拟 EventSource(尝试了大部分模拟策略),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60827742/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com