Unit test produced an unforeseen outcome when executing the function with the setTimeout() method

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.

Answer №1

If you want to simulate setTimeout, and observe the behavior of console.log, you can do so using Jest. No need for async/await in this case, as your defer() function does not rely on promises.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

The necessity of utilizing a dummy object for storing events in JavaScript is evident in certain situations

I am confused as to why in some instances a dummy object is needed in JavaScript to store events, like in the following code: Metal.Gold = function() { var temp = $("<div>"); //dummy object this.Submit = function(url1, method, data){ ...

The Javascript code is failing to run following an ajax request

When I use XMLHttpRequest.send to call a php script that contains some javascript code, the javasript in the called php script does not run. The process of making the call: var formdata = new FormData(); formdata.append("uploadfilename", file); var ajax ...

Tips on transforming a grouped object into a table organized by column with the help of Lodash

Looking at my array data: [{ id: '1234', year: 2019 , name: 'Test 1- 2019', rate: 1}, { id: '1234', year: 2020, name: 'Test 2 - 2020', rate: 2 }, { id: '1234', year: 2020, name: 'Test 3 - 2020&apos ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Guide on dynamically updating a div in PHP with a mix of text output and images at regular intervals

My current project involves creating a browser-based card game primarily using PHP, with potentially incorporating other languages to help me enhance and test my PHP skills. However, I've encountered difficulties while attempting to implement various ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

Preventing preventDefault() from firing in JQuery only when necessary

I have come up with a script that I recently created. <script> $(document).ready(function(){ $('a').data('loop',true); $('body').on('click', 'a', function(event){ console.lo ...

Combine and interchange horizontal and vertical form designs within antd 5 for a personalized touch

I need to customize the layout of a form to display checkboxes in vertical mode. Specifically, there is a row of checkboxes that I want to appear vertically aligned rather than horizontally. In the past, I was able to achieve this in antd 4 by applying a ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

What is the significance of the appearance of the letters A and J in the console for Objects?

After running console.log() in JavaScript code, you may notice some random letters like A and j before or after the Object description in the Google Chrome browser console. What is the significance of these letters? ...

Issue with Vue/Nuxt 3: Unable to modify properties of null when setting 'textContent'

I am currently facing an issue with a function that is designed to switch words every few seconds. The functionality itself is working fine, but I keep encountering the following error intermittently in the VSC console: TypeError: Cannot set properties o ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

update the variables based on the changes in the service

I have developed a service in my application to retrieve configuration settings from the database. This service is used to display various configurations across different parts of the app. However, I am encountering an issue where the variables do not upda ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

The significance of documenting and optimizing code execution

My coding practice is to always (or at least try to) add comments to my code. However, I have set up my server to delete those comments and extra white space before the final delivery. Should I omit comments from the live system's code (Javascript/php ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...