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

132
Visualizações
Jest tests finishing before asynchronous sqlite3 callback functions in typescript

So in the first file, let's say db.ts - it exports a function, let's call it dbHandler, with content similar to the following:

try {

    let db = new sqlite3.Database('./sampleDBName.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err: Error) => {
        if (err) {
        console.error(err.message);
        }
        console.log('Connected to the database.');
    });
    
    db.serialize(function() {
        db.run("CREATE TABLE IF NOT EXISTS sample_table (id VARCHAR, sample_data INTEGER, PRIMARY KEY (id))") // ensure table exists

        .run("INSERT OR IGNORE INTO sample_table (id, sample_data) VALUES ($1)", ['1',1]) // ensure row exists
        .all("SELECT * FROM sample_table WHERE id = $1", [1], async (error: Error, rows: Array<any>) => {
            if(error) {
                console.log(error);
            }
            // logic in here (calls other functions & more based on data in rows)
            sampleObjectMock.objectFunc({content: "sample content"});
        });
    });
    
    db.close((err: Error) => {
        if (err) {
            return console.error(err.message);
        }
        console.log('Close the database connection.');
    });
} catch(e) {
    console.log(e);
}

And in the index.spec.ts (test) file:

describe("sample use case", () => {       
    it("sample test", async () => {           
        let sampleObjectMock = { 
             objectFunc: jest.fn()  
         }  
         await dbHandler(sampleObjectMock);  
         expect.assertions(1);  
         expect(sampleObjectMock.objectFunc).toHaveBeenCalledWith({content: "sample content"});  
     }  
}

I'm getting errors stating the following for each console log in opening and closing the database:

"Cannot log after tests are done. Did you forget to wait for something async in your test?"

In addition to this, the 'objectFunc()' is never called, it works outside of the jest testing environment - I believe it doesn't work due to the callback functions of the database calls only running after the tests themselves have already run to completion asynchronously. Any ideas?

I have tried adding jest.runAllTimers() or jest.runAllTicks(), but I have little experience with these types of functions and they didn't seem to change anything. Thanks in advance if anyone can help with this.

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