I'm trying to make a test with jest and promises.
When I try to write in console the result get it from the promise I've got an undefined value
This is my testing code:
describe("Search concurrent with promises", () => {
describe("Test 10: Several searches in DDBB", () => {
function connection(){
let ddbb = new PGMappingDDBB();
return new Promise((resolve, reject) => {
let db = ddbb.connect();
//resolve("Hello World");
resolve(db);
});
}
test("Test 12: Several searches concurrently", () => {
connection().then(ddbb => {
console.log(ddbb);
});
});
});
});
ddbb.connect() is an asynchronous function. The code of connect() is:
async connect(){
this.client = await poolMapping.connect();
}
When I try to write the state of the variable ddbb I've got that is undefined.
However, If I comment resolve(db) and remove the comment of resolve("Hello World"), when I write the value of ddbb I've got "Hello World".
What am I doing wrong?
Edit I:
ddbb.connect() returns a Promise. If I write what returns console.log(ddbb.connect()). I've got:
Promise { <pending> }
To explain:
async connect(){
this.client = await poolMapping.connect();
// NOTE: There is no return value
}
describe("Search concurrent with promises", () => {
describe("Test 10: Several searches in DDBB", () => {
function connection(){
let ddbb = new PGMappingDDBB();
return new Promise((resolve, reject) => {
let db = ddbb.connect();
// ^^ this will be undefined, as connect has no return value
resolve(db);
// ^^^^^^^^^^^^ Resolving the promise with undefined
});
}
test("Test 12: Several searches concurrently", () => {
connection().then(ddbb => {
console.log(ddbb);
/// ^^^^ will be undefined
});
});
});
});
Additionally, jest is not waiting for the outcome of the promise, and you are not asserting anything in the test, so it will always succeed.
When dealing with promises, if you return the promise from the test, Jest will wait for it. But you still need to assert on the value.