last day (15 days later) » 

12:47
0
Q: Ensuring Document is Retrieved Without Using setTimeout() in Mocha Test

MuirikI have written some tests in my Node project using Mocha and Chai. In one of my tests I create an agenda.js job, and then save it to the database. Then I retrieve that document from my MongoDB database and run some checks on it. After numerous configurations, I've found a construction for the tes...

Personally I would just use the 'done' callback like this: before(function(done){ /* some awaiting async code, done(err) */ });
I'm using async/await - so it should be equally effective. Either one handles async code and ensures the code is executed before moving on. I will try it though - to see if it makes any difference.
ok, you have the outer before seems to be working fine, so what's different about the inner before? Is client.connect resolving before the awaits inside the async callback that gets passed to it?
I tried using the done() callback instead of the promise-based async/await construction in the before block. Exactly same result. Only works with the addition of the setTimeout() block.
I don't know. But regardless, why would the it block run before everything defined in the before block is completed?
try returning the await in the before
12:47
There are two awaits there. Which one do you mean?
the it will run before the before has finished an async function if the before is returned a resolved promise.
The final await
Okay, so what do you suggest? I tried explicitly returning result in the before block. Still didn't work. The second half of the it checks pass, because it resolves half-way through those checks being run currently.
before(function (done) {
client.connect(async function (err) {
assert.equal(null, err);

const db = await client.db(dbName);

result = await db.collection("jobs").findOne({
"name": jobName
});

return result;


});
done();
});
Tried this. Same result.
`
...
before(async function () {
return new Promise((resolve, reject) => {
await client.connect(async function (err) {
if(err) return reject(err);
try {

const db = await client.db(dbName);

result = await db.collection("jobs").findOne({
"name": jobName
});

client.close();
} catch(err){
return reject(err);
}
return resolve();
});
});
});
...
`
sorry I don't know how to format it
Will try this, thanks.
I wouldn't assert in a before block
ithe code is wrong.
it needs to be
return new Promise(async function(resolve, reject) { ...
12:55
You mean you wouldn't 'await'?
Yes, I removed that.
And with the 'await' removed it worked!
Many thanks, @George!
If you want to add this answer I'll mark it as correct.
congrats, nice :)
This peice of code? OK sure.
Great, thanks.

last day (15 days later) »