Reputation: 315
I have been using Mocha for testing in Node because it seems to be what most people use. I am also using MongoDB to store my data and since my server is a simple API server pretty much all of my methods are just plain database queries which I am trying to test with Mocha. Now the Issue that I am facing is that (besides the fact that it seems to be quite hard to test async functions in general) I can not seem to find a proper way to test for a mongoDB excpetion.
it('Should not create account', async (done) => {
try {
await createAccountDB(user);
await createAccountDB(user);
} catch (err) {
assert.notEqual(err, null);
console.log(err);
}
finally {
done();
}
});
});
What I am trying here is to create an account for a User (Basically just saving the Object to the db) and then creating the same account again which should result in a duplicate key error.
Now, this doesn't work and as far as I can tell that is because i have defined both async and done. The reason why I did this is, if I don't define async I would need to have a whole bunch of .then and .catches which would make the code look horrible but if I don't include then done() in the finally block, my test seems to never even make it to the catch block.
Is there any way to write tests like these in Mocha which don't make your code look absouletly horrible?
Upvotes: 1
Views: 46
Reputation: 1639
Since you're already using the async/await
model you don't necessarily need the done
callback for the test case. Certain versions of mocha will warn you when you have more than one means of indicating test completion. Try this:
it('should not create an account', async function() {
try {
await createAccountDB(user);
await createAccountDB(user);
throw new Error('Did not reject a duplicate account');
} catch (err) {
assert.notEqual(err, null);
// any other assertions here
}
});
The error thrown in the try/catch
block is very important - without it, the test will still pass even if the error is not thrown.
Upvotes: 1