Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda