Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired.

I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others.

Now, I have implemented a new piece of code that eliminates the need for the use of "any".

  let defaultTimeout: typeof globalThis.setTimeout;
  beforeEach(() => {
    defaultTimeout = global.setTimeout;
    globalThis.setTimeout = (callback: TimerHandler) => { (1)
      defaultTimeout(callback, 500);
    };
  })

Despite these changes, I am still encountering an error related to globalThis.setTimeout.

TS2741: Property promisify is missing in type (callback: TimerHandler) => void but required in type typeof setTimeout timers.d.ts(161, 19): promisify is declared here.

While I am aware that using any and unknown could resolve this issue, I am curious if there is an alternative solution available?

Answer №1

It is not recommended to override functions like setTimeout, setInterval, console.*. Have you considered using timer mocks instead? Why resort to this method?

I see that you may be using Jest or Vitest, but the approach remains the same.

If your aim is simply to bypass the timers, you could try this:

jest.useFakeTimers();

// Your test code can go here...

expect(true).toEqual(true);

jest.runAllTimers();

jest.useRealTimers();

The line jest.runAllTimers(); is crucial in accelerating the timers and advancing them quickly. For more information, visit: https://jestjs.io/docs/jest-object#jestrunalltimers

Answer №2

After being inspired by @Tal Rofe, I decided to revisit the problem:

I was unaware that jest could be used to mock global functions... so here is my updated solution:

jest.useFakeTimers();
type TimeoutType = ReturnType<typeof globalThis.setTimeout>;
const spyOn = jest.spyOn(global, 'setTimeout');
spyOn.mockImplementation((callback: (args: void) => void): TimeoutType => {
  callback();
  return <TimeoutType>(<unknown>0); // timeout is actually a number!
});

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

How to generate an array within a TypeScript extension function

As I was working on creating an extension method using typeScript, the main goal was to establish a static or normal variable within the method. The ServiceCollector method was invoked three times in order to send and store data or objects in an array. B ...

Passing object attributes to a modal in AngularJS

I am trying to figure out how to pass a complete object to my modal so that I can view all of its attributes there. Currently, the items I have look like this: $scope.items = [{ Title: title, Id: id }] On my html page, I am using 'ng-repeat' as ...

Working with Javascript: Navigating a dynamic array of elements

I need to reorganize a form on my webpage. Currently, all the fields are in one table and I want to move them around based on certain conditions. However, when I try to loop through the elements and move them, the javascript array is changing and causing m ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

Ways in which this data can be best retrieved

Hey there, I'm currently in the process of building an Ionic2 app with Firebase integration. Within my codebase, there's a provider known as Students-services where I've written a function to navigate through a node, retrieve values, and dis ...

retrieve the variable contained within the callback function

const axios = require('axios'); const options = { url: 'https://api.github.com/repos/axios/axios', headers: { 'User-Agent': 'axios' } }; function handleResponse(error, response, body) { if (!error && re ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Implementing a NextJS client component within a webpage

I am currently working with NextJS version 14 and I am in the process of creating a landing page. In one of the sections, I need to utilize the useState hook. I have specified my component as "use-client" but I am still encountering an error stating that " ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Creating a JavaScript-powered multi-department form: A step-by-step guide

Is there a way to maintain the form displayed on a webpage created in HTML5 and JavaScript for logging calls across three different departments? With buttons assigned to each department, clicking on them reveals the respective HTML form. That said, every t ...

Is it possible to dynamically add plotLines to the xAxis using datetime in HighCharts?

Hey there! I've been playing around with adding plotlines in Highcharts and I'm loving it. It's really easy to define a date time on the xAxis for a plotline, like this: xAxis: { plotLines: [{ color: '#dadada', ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Issue with Vue directive bind not functioning after element refresh

My approach involves utilizing vue.js to create forms, where all fields are structured within a JavaScript objects array. Here is an example of the structure I use: { type: "input", mask: "date", default: "2018/04/14" }, { type: "input", ...

Live Search: Find Your Answers with Ajax

I've come across this issue multiple times, but haven't found a solution that fits my specific requirements. I've encountered several URLs with links like example.com/ajax/search?query=Thing I'm currently working on a header and using ...

Dynamic search form technology

My HTML view includes a search form and AJAX code to handle the form request $(document).ready(function() { console.log('Ready'); $('.search-wrapper').on('click', '#find-dates', function(a) { a. ...