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

133
Views
Test interaction with two interval async functions

Using jest 27.4.5 and sinon 12.0.1, I want to test the interaction between two interval functions of which one is async.

Here's my simplified code

module.exports = class MyClass {
    one() {
        console.log("one", Date.now())
    }    
    async two() {
        await Promise.resolve()
        console.log("two", Date.now())
    }
    init() {
        setInterval(this.one, 100)
        setInterval(this.two, 150)
    }
}

And here's the test:

const sinon = require("sinon")
const MyClass = require("./index")

describe("My test suite", () => {
    test("My test", async () => {
        const sandbox = sinon.createSandbox()
        const clock = sandbox.useFakeTimers()
        const myInstance = new MyClass
        myInstance.init()
        clock.tick(500)
    })
})

Now, it seems to me that the promise inside the async interval function is always executed after all executions of the first function:

Expected output:

one 100
two 150
one 200
one 300
two 300
one 400
two 450
one 500

Actual output:

one 100
one 200
one 300
one 400
one 500
two 500
two 500
two 500

The real life use case is: Interval function one does something quite often and function two asynchronously checks and sets some configs which function one uses. In order to check whether function one actually uses the expected configs, I need those functions to be executed in the right order in the test.

In the real-life environment, I have an additional problem: Some async interval function which does database queries logs "real" Unix times instead of faked ones upon console.log(Date.now()), e.g. 1641284903075 in the test. But I couldn't reproduce that behavior in a minimal example.

Making both functions async didn't help either in real-life. The execution order in the test still seems random and not according to interval times.

Edit: In real life, the interval values are as high as half an hour. So, I have to use fake timers. Actually waiting is not an option in unit tests.

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!