While running a Jest test that adds shift entries to a MongoDB collection using Mongoose, I see this error in the console:
node_modules/jest-jasmine2/build/jasmine/Env.js:198 Unhandled error
node_modules/jest-jasmine2/build/jasmine/Env.js:199 Error at model.wrappedPointCut [as save] ...
My test uses expect.assertions(3) and returns a promise, and the relevant code calls emp.save() inside a Promise.all. The test passes, but Jest still logs the unhandled error. Why does jest-jasmine2 report this unhandled error, and how can I fix it when saving Mongoose documents inside tests?
The error usually happens when a promise rejects but isn’t caught. In your case, emp.save() inside Promise.all may throw, and even if the test passes, Jest sees an unhandled rejection. Try adding await and a catch:
await Promise.all(employees.map(emp => emp.save().catch(err => console.error(err))));
Or handle it in your test explicitly:
test('save employees', async () => {
expect.assertions(3);
try {
await Promise.all(employees.map(emp => emp.save()));
} catch (err) {
console.error('Save failed:', err);
}
});
This way, all rejections are handled, and Jest won’t report unhandled errors.
Mongoose queries return thenables that sometimes behave differently from native Promises. Wrapping .save() in .exec() can make sure Jest tracks the promise properly:
await Promise.all(employees.map(emp => emp.save().exec()));
If you can’t use .exec() with .save(), just wrap the promise:
await Promise.all(employees.map(emp => new Promise((resolve, reject) => {
emp.save(err => err ? reject(err) : resolve());
})));
This ensures Jest sees all async operations and handles errors correctly.
Sometimes this happens if Jest thinks your test is synchronous but async operations are still running. Make sure your test function is marked async and you return or await all promises:
test('save employees', async () => {
expect.assertions(3);
const results = await Promise.all(employees.map(emp => emp.save()));
expect(results.length).toBe(3);
// other assertions
});
Also, avoid mixing done callbacks and promises—Jest can get confused and log “Unhandled error” even if the test passes.