How to make a query in the Postgress database asynchronously for testing in cypress?

Viewed 41

I am trying to get data from the database through an exported function. But the problem is that the function is returning empty data. The query works if executed outside the function, but when I put the query inside the function, the return is empty. I believe that the function is returning before the query gets the result from the database.

My code:

export function queryDb(query) {
    return new Promise(() => {
        database.select(database.raw(query).then(data => {
            return data;
        }).catch(err => {
            console.log(err.message);
        })
        )
    })
}
1 Answers

I think you need resolve and reject in your function

export function queryDb(query) {
    return new Promise((resolve, reject) => {
        database.select(database.raw(query).then(data => {
            resolve(data);
        }).catch(err => {
            console.log(err.message);
            reject(err)
        })
        )
    })
}

If you turn that into a Custom Command, Cypress will await the resolve before moving on, which is handy to keep the sequence of things correct in the test.

// cypress/support/commands.js

Cypress.Commands.add('queryDb', (query) => {
    return new Promise((resolve, reject) => {
        database.select(database.raw(query).then(data => {
            resolve(data);
        }).catch(err => {
            console.log(err.message);
            reject(err)
        })
        )
    })
}

// in test

cy.queryDb(myQueryString).then(data => {
  // assert data is correct
})
Related