When manually testing this code in the browser's console, it performs as expected. The correct number of points is displayed with a one-second delay in the console.
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
However, I am having difficulty writing an effective unit test in index.test.js file. Other tests are passing successfully, indicating that the Babel and Jest configurations are correct. I tried looking into async and await concepts but couldn't figure out how to apply them to my specific code. The following test case is failing:
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);
});
I need help understanding how to prevent setTimeout() from causing my unit test to fail. Any guidance on this would be greatly appreciated.