Reputation: 667
DB: Mongo ODM: I am using Mongoose as the ODM.
I am writing negative tests for document.save() function for my app. How do I simulate or replicate an error while saving the document so that I can assert accordingly.
const CreateArtist = async (artist) => {
try {
await dbConnect();
const user = await new Artist(artist);
await user.validate();
return await user.save(); // want to test for error on save.
} catch (err) {
throw err;
}
};
I have tried changing the connection string, but I got the connection string wrong error. I am unsure how to replicate the error on save.
Upvotes: 2
Views: 1123
Reputation: 583
You could try writing a pre-save function that returns an error:
user.pre('save', function(next) {
return next(new Error('myCustomError'));
});
user.save() // throws myCustomError
adapted from the docs here
Upvotes: 5