在玩笑中测试事件侦听器的最简单方法是什么?

What is the easiest way to test event listeners in jest?

我正在尝试测试以下功能

 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=>{.....})
};

笑话测试: // 在 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 上找到了间谍。

与其模拟它的实现,不如使用它来获取回调函数。

然后就可以直接调用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!
});