Fix the error of erros not being returned in async functionI have this code:
Jul 23, 2017 · 1 min read
I have this code:
this.findUser = async function(args) {
assert(args.email, "email is required");
let result = mongoDB.collection('users').findOne(args);
return result;
};in my unit test, this function would return a null, so it can be catched by the unit test:
This is the method that use the above method:
let checkUserExists = async function (app) {
let result = await dbWrapper.findUser({email: app.email});
if (result) {
app.setInvalid("email exists");
throw app;
} else {
return app;
}
};And this is the unit test:
describe('email exists', function () {
let regResult;
beforeAll(async function (done) {
await db.collection('users').remove({});
await registration.applyMembership({
email: "a@a.com",
password: "a",
confirm: "a"
});
regResult = await registration.applyMembership({
email: "a@a.com",
password: "a",
confirm: "a"
});
done();
});
it('should not be successful', function () {
regResult.success.should.be.false;
});
it('should have message', function () {
regResult.message.should.equal("email exists");
});
});But when I use paw to query the route, the null would not be catched by those code. Instead, it is thrown and be catched by the outer-most try-catch block;
app.post('/auth/registration', async (req, res) => {
let result = await membership.register(req.body);
if (result.success) {
res.status(200).json({success: true});
} else {
res.status(400).json({success: false, message: result.message});
}
});Here, the result.message would be null. But not in the unit test.
The solution is to use try-catch for the mongo driver query:
this.findUser = async function(args) {
assert(args.email, "email is required");
try {
let result = mongoDB.collection('users').findOne(args);
return result;
} catch (err) {
return err;
}
};Then, it works in both for Paw and unit test.
