以下代碼在瀏覽器控制臺中手動測驗時按預期作業。我在控制臺中延遲一秒收到正確的點數。
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 配置很好)。我搜索了 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() 未能通過單元測驗,我將不勝感激。
uj5u.com熱心網友回復:
你可以嘲笑setTimeout,也可以窺探console.log。您不需要在這里使用async/ await,您的defer()函式不使用承諾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410567.html
標籤:
上一篇:如何測驗內部功能
