Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jest with async function calls before and after setTimeout #10290

Closed
lavish-jain opened this issue Jul 20, 2020 · 6 comments
Closed

Jest with async function calls before and after setTimeout #10290

lavish-jain opened this issue Jul 20, 2020 · 6 comments

Comments

@lavish-jain
Copy link

lavish-jain commented Jul 20, 2020

馃悰 Bug Report

The scenario:- Using jest with nodejs, the function to be tested calls one async function, then calls a sleep function (wrapper over setTimeout to wait for a specific period of time), and then calls another function (not necessarily async).

While testing this with jest.useFakeTimers() and jest.advanceTimersByTime()/jest.runAllTimers()/jest.runOnlyPendingTimers(), the first function and the sleep function gets called, but the code after the call to sleep function is not executed. The coverage report confirms that the lines after sleep function are not executed.
The test passes.

Everything works as expected when func1 is synchronous.

How Can I make this work?

To Reproduce

Here is a basic example:-

index.js

const func1 = async() => {
    setTimeout(()=>{console.log('func 1...')}, 1000);
}

const func2 = async() => {
    setTimeout(()=>{console.log('func 2...')}, 1000);

}

const sleep = ms => {
    console.log(`Sleeping for ${ms/1000} seconds`);
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    })
}

const main = async() => {
    try {
    await func1();
    // Sleeping for a long long time
    console.log('Before Sleep');
    await sleep(2000000);
    console.log('After Sleep')
    await func2();
    return 'success';
    } catch(err) {
        console.log(err);
        return 'error'
    }
}

index.test.js

const index = require('./index');
jest.useFakeTimers();

describe('Testing index.js...', () => {
    test('Should return success', async() => {
        const promise = index();
        jest.advanceTimersByTime(2000000);
        promise.then(response => {
            expect(response).toBe('success');
        }) 
    });
})

Expected behavior

Test to pass with the following logging into console:-

func 1...
Before Sleep
Sleeping for 2000 seconds
After Sleep
func 2...

Actual behaviour

Test passes with the following logging into console:-

func 1...
Before Sleep
Sleeping for 2000 seconds

Link to repl or repo (highly encouraged)

GitHub Repo for the above code

envinfo

System:
    OS: Linux 5.4 Ubuntu 20.04 LTS (Focal Fossa)
    CPU: (4) x64 Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz
  Binaries:
    Node: 13.14.0 - /bin/node
    npm: 6.14.4 - /bin/npm
  npmPackages:
    jest: ^25.5.4 => 25.5.4 
@lavish-jain
Copy link
Author

The following workaround works when func2() is synchronous:-

In index.test.js, replace

jest.advanceTimersByTime(2000000);

with

Promise.resolve().then(()=>{jest.advanceTimersByTime(2000000)});

But the above change gives the following output when func2 is async:-

func 1...
Before Sleep
Sleeping for 2000 seconds
After Sleep

@sreetamdas
Copy link

this should help: https://stackoverflow.com/questions/52177631/jest-timer-and-promise-dont-work-well-settimeout-and-async-function

@lavish-jain
Copy link
Author

Hi @sreetamdas I had already tried that before. The output hangs at the call of the sleep() method (with the console showing no output after Sleeping for 2000 seconds), but the test passes. The test passes even when we change the return value from success to some gibberish in the main() function.

Apparently, useFakeTimers breaks when used with native promises. It is a known issue in jest for almost 2 years now.

@github-actions
Copy link

This issue is stale because it has been open for 1 year with no activity. Remove stale label or comment or this will be closed in 30 days.

@github-actions github-actions bot added the Stale label Feb 17, 2023
@github-actions
Copy link

This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Mar 19, 2023
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 23, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants