I have a function that writes data to a mongodb, like so:
const writeToDB = async (db, data) => {
const dataKeys = Object.keys(data)
dataKeys.forEach(async key => db.collection(key).insertMany(data[key]))
}
This works fine if I run it in a node script. But when I tried to use it in Jest's beforeAll
I got this async error from Jest:
Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests.
after some troubleshooting I found out that forEach
was causing the trouble. Using a for loop solved this problem:
const writeToDB = async (db, data) => {
const dataKeys = Object.keys(data)
for (const key of dataKeys) {
await db.collection(key).insertMany(data[key])
}
}
Searching for this problem I came across this article: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
The explanation there made sense, but it left me with some questions:
- According to the article, it should not have worked even in the node script. How come it did?
- Why is executing it in node different from running it in Jest?
edit
After reading all the comments, I realise my first question was a bit nonsense. Normally I assign the result of an async function to a variable, and if I don't put await, there will an undefined error down the line. But that's not the case here, so script exits normally and the db writes happen concurrently in the background.