Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda