我正在尝试测试以下功能
getVal(process) {
test.on('data', async data => {
try {
for (const val of data) {
await process(val);
console.log('processed')
}} catch (e) {}
});
test.on('error', err => {
console.log('error', err)
});
}
process(payload) {
return new Promise(resolve=>{.....})
};
开 Jest 测试: //在 beforeEach 中
mockData =[an array containing 10 values]
onSpy = jest
.fn()
.mockImplementationOnce(async (data, callback) => {
callback(mockData);
})
.mockImplementationOnce((error, callback) => {
callback(mockErr);
});
it('should trigger callback once per message', async () => {
await xyz.getVal(process);
await expect(process).toHaveBeenCalledTimes(10);
});
我预计 process()
会被调用 10 次,因为数据发送了 10 次。然而,当我断言时,它仅被调用 2 次,但当我将 console.log 放入函数本身并运行测试时,它被调用 10 次。
我不确定出了什么问题。感谢任何帮助。
最佳答案
问题是,在 xyz.getVal
上调用 await
实际上不会执行任何操作,因为 getVal
是一个同步函数,只是设置事件监听器...
...因此,当 expect
运行并失败时,异步事件尚未完成处理。
看起来您已经在 test.on
上发现了 spy 。
不用模拟它的实现,只需使用它来获取回调函数即可。
然后您可以直接调用并await
回调函数:
// in beforeEach
mockData = [an array containing 10 values]
onSpy = jest.fn();
it('should trigger callback once per message', async () => {
xyz.getVal(process);
const callback = onSpy.mock.calls[0][1]; // <= get the callback (second argument of the first call to test.on)
await callback(mockData); // <= call and await the callback directly
expect(process).toHaveBeenCalledTimes(10); // Success!
});
关于javascript - 在 Jest 中测试事件监听器的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822102/