Incorporating Jest alongside setTimeout and leveraging useFakeTimers

As I work with a TypeScript async function that requires a 1-second sleep between two statements, this implementation is in place:

async function systemUnderTest(): Promise<void> {
    console.log("One");
    await new Promise(r => { setTimeout(r, 1000); });
    console.log("Two");
}

To test this function within the Jest framework, the following test can be executed:

test('myTest', async () => {
    await systemUnderTest();
});

While this test functions using real time, the question arises - How can this function be tested in fake time?

An attempt was made to write the following test for testing in fake time:

test('myTest', async () => {
    jest.useFakeTimers();
    await systemUnderTest();
    jest.runAllTimers();
    jest.useRealTimers();
});

However, upon executing this test, it exceeds the 5-second timeout and fails to print "Two".

Answer №1

Could you attempt the following steps:

  1. Initiate the async function without pausing for it.
  2. Execute all timers.
  3. Subsequently, pause for the async function to complete.
test('myTest', async () => {
    jest.useFakeTimers();

    const promise = systemUnderTest(); // trigger the function without waiting for it

    jest.runAllTimers(); // this will execute the setTimeout in systemUnderTest

    await promise; // now we can wait for the function to finalize

    jest.useRealTimers();
});

Please bear in mind that with fake timers, the setTimeout callback will be triggered synchronously upon running jest.runAllTimers(), hence awaiting it beforehand is unnecessary.

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

Use middleware for multiple routes with just one call

I have an API for a dashboard which includes routes such as: /dashboardRoutes/getdata1 /dashboardRoutes/getdata2 . . . /dashboardRoutes/getdata7 On the backend, I am using express router.use to direct these routes to a handler. router.use('/dashboard ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

How can we ensure that the element being hovered over is brought to the forefront and placed in the center?

I have been tasked with replicating this specific object for a project. The creation process is going smoothly, but now the requirement is to make it stop when the user hovers over it. Implementing this hover functionality is not a problem as CSS provides ...

Struggling to make the JavaScript addition operator function properly

I have a button that I want to increase the data attribute by 5 every time it is clicked. However, I am struggling to achieve this and have tried multiple approaches without success. var i = 5; $(this).attr('data-count', ++i); Unfortunately, th ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

An option instead of using a pop-up window

Currently, I have a PHP script and a small form that allows users to upload image files. The user can access this feature by clicking on a button on the parent HTML page, which opens up a Pop Up Window. I understand that not everyone is a fan of 'Pop ...

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Combatting repetitive code through the use of Redux toolkit and actions

My code is currently long and repetitive. I realize that using helper functions would help me cut it down and make it more maintainable and readable. As a React beginner, I have a question: Should I implement most of this logic with helper functions in a s ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

How to Improve Performance for 15,000 Socket.io Users

I am facing an issue with my chat application that has large chatrooms, with 15,000 users connected to a single room. Only a few have the privilege to write messages, so in theory, there should not be a significant load on the server. However, I have obser ...

Can you confirm if this is the most efficient method for loading google-analytics and jQuery?

It's not necessary for jQuery to be loaded immediately on page load: Here is what I currently have: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '...']); _gaq.pus ...

WebRTC functions effectively within the same network, but encounters difficulty when communicating between different IP addresses

Please find my code on Github: https://github.com/rashadrussell/webrtc_experiment/blob/master/public/script.js I am currently working on developing a 1-to-1 video conferencing script using WebRTC. The script is hosted on AppFog, a cloud hosting platform. ...

Using Typescript to inject `require(...)` rather than importing files

I am currently in the process of compiling a third-party module called pdfassembler and I want to ensure that the source code for the import statements is included in the compiled output instead of references to require statements. Within the src/pdfassem ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

Resetting the caret position in a React Native TextInput occurs when switching the secureTextEntry prop

As I develop a component to wrap the React Native TextInput in my app, I encounter an issue with the caret position resetting to 0 when toggling the secureTextEntry prop for password visibility. To address this problem, I implemented a workaround using a s ...