Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
How to test the data logged into a console with the delay due to setTimeout()

I have a wrapper function defer that delays implementation of any other function:

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

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

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

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

I want to run a unit test which will test what data is logged into a console but I fail to take control of the timer, so the test will be passed.

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 = defer(playerPerformance.points, 1000);

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

Please help me develop this unit test to pass the test.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!