I have a small test (Mocha/Chai), which tests that the encryptPass function returns the correct hash:
const assert = require('chai').assert;
const bcrypt = require('bcrypt');
var encryptPass = require('../../shared/helpers/encryptPass.js');
var createUUID = require('../../shared/helpers/createUUID.js');
describe('encryptPass', function() {
it('returns correct password hash', () => {
var pass = createUUID();
var encryptedPass = encryptPass(pass);
Promise.all([pass, encryptedPass]).then(values => {
let [pass, encryptedPass] = values;
var compareResult = bcrypt.compareSync(pass, encryptedPass);
assert.equal(compareResult, true);
});
});
});
My concern is that there is that the assertion is assuming that the Promise.all function will work without throwing an error. How best to handle this?
Just return the promise that results from your test:
it('returns correct password hash', () => {
var pass = createUUID();
var encryptedPass = encryptPass(pass);
// Just return...
return Promise.all([pass, encryptedPass]).then(values => {
let [pass, encryptedPass] = values;
var compareResult = bcrypt.compareSync(pass, encryptedPass);
assert.equal(compareResult, true);
});
});
This will take care of telling Mocha that your test is asynchronous. In your original code, Mocha won't wait for the test to complete. Returning the promise forces it to wait. Secondly, by returning the promise you also control whether the test will be successful or not. If any of the promises passed to Promise.all
is rejected, that's a test failure. If the code in your .then
handler fails, that's also a test failure. For instance if assert.equal
fails, an AssertionError
is raised, which results in a promise rejection, which Mocha treats as a failure.