运行 对包含 setTimeout() 的函数进行单元测试时出现意外结果

Unexpected result while running a unit test for the function containing setTimeout()

以下代码在浏览器的控制台中手动测试时按预期工作。我在控制台中收到了正确的点数,但延迟了一秒钟。

const defer = (func, ms) => {
  return function() {
    setTimeout(() => func.call(this, ...arguments), ms);
  };
};

const playerPerformance = {
  goals: 33,
  assists: 21,
  points(penaltiesEarned) {
    console.log((this.goals * 2) + (this.assists * 1.5) + (penaltiesEarned * 1.5));
  },
};

const deferredPointsDisplay = defer(playerPerformance.points, 1000);

deferredPointsDisplay.call( { goals: 18, assists: 19 }, 7 ); // in 1 sec: 75

但是,我很难在 index.test.js 中编写有效的单元测试(其他测试 运行 完美,所以 babel 和 jest 配置没问题)。我在 google 上搜索了 async 和 await 的想法,但是,我在网上找到的例子并没有帮助我理解如何将它正确地应用到我的代码中。以下测试失败:

    it('should return 75', () => {

  const playerPerformance = {
    goals: 33,
    assists: 21,
    points(penaltiesEarned) {
      console.log((this.goals * 2) + (this.assists * 1.5) + (penaltiesEarned * 1.5));
    },
  };
  
    const consoleSpy = jest.spyOn(console, 'log');

    const deferredPointsDisplay = defer2(playerPerformance.points, 1000);

    deferredPointsDisplay.call( { goals: 18, assists: 19 }, 7);
  
    expect(consoleSpy).toHaveBeenCalledWith(75);
});

如果你能帮助我理解如何防止 setTimeout() 使我的单元测试失败,我将不胜感激。

你可以mock setTimeout and you can spy on console.log。你不需要在这里使用 async/await,你的 defer() 函数不使用承诺。