Typescript 如何使用jest和TS模拟EventSource(尝试了大部分模拟策略)
想要使用jest模拟EventSource,但一直抛出Typescript 如何使用jest和TS模拟EventSource(尝试了大部分模拟策略),typescript,unit-testing,jestjs,Typescript,Unit Testing,Jestjs,想要使用jest模拟EventSource,但一直抛出引用错误:未定义EventSource 请看一下代码。非常感谢 // eventSourceHandler.ts export default new class A() { listenEventSource(){ const eventSource = new EventSource(url); eventSource.addEventListener("something", callSomething); ev
引用错误:未定义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不断抛出错误,说类型global上不存在EventSource
有没有人想分享一个更好的嘲笑策略?
我们将对此表示高度赞赏
谢谢guyzz…好吧,我想你可以使用两种选择
- 将eventSource实例注入正在使用的类中,以便可以对其进行模拟
- 使用生成器函数,而不是在类a中直接调用构造函数
对于后者,您可能会得到如下结果:
utils.ts
然后在你的测试课上:
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 {}
});
我希望有帮助你试过了吗
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 {}
});