繁体   English   中英

为包含 setTimeout() 的 function 运行单元测试时出现意外结果

[英]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 配置很好)。 我搜索了异步和等待的想法,但是,我在 web 上找到的示例并没有帮助我理解如何将其正确应用于我的代码。 以下测试失败:

    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() 未能通过单元测试,我将不胜感激。

您可以模拟setTimeout并且可以 监视console.log 您不需要在这里使用async / await ,您的defer() function 不使用承诺。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM