Home > front end >  Unexpected result while running a unit test for the function containing setTimeout()
Unexpected result while running a unit test for the function containing setTimeout()

Time:01-13

The following code works as expected when testing it manually in the browser's console. I receive the correct number of points with the delay of one second 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 struggle to write an effective unit test in index.test.js (other tests are run perfectly, so the babel and jest configurations are fine). I googled the idea of async and await, however, the examples I found on the web did not help me understand how to apply this correctly to my code. The following test fails:

    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 would appreciate if you help me understand how I can prevent setTimeout() from failing my unit test.

CodePudding user response:

You can mock setTimeout and you can spy on console.log. You don't need to use async/await here, your defer() function doesn't use promises.

  •  Tags:  
  • Related