Reputation: 1393
I am trying to test my password hashing function but I keep on getting failures due to some TypeError error.
I am sure the function works since I tried to call it from some other file and I get the expected result without any error.
Here is the function:
exports.hashPassword = (password) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(salt_length, (err, buf) => {
if (err) reject(err);
const salt = buf.toString('base64');
crypto.pbkdf2(password, salt, iterations, keylen, digest, (err, key) => {
if (err) reject(err);
const hashedPassword = '{X-PBKDF2}:'+digest+':'+keylenB64+':'+iterationsB64+':'+salt+':'+key.toString('base64');
resolve(hashedPassword);
});
});
});
};
Here is the test that fails:
describe('users', () => {
describe('utils', () => {
it('should hash a password', (done) => {
const password = 'secret';
utils.hashPassword('secret')
.then((hash) => {
console.log('Hash: '+ hash);
done();
})
.catch((err) => {
console.log(err);
done(err);
});
});
});
});
And this is the 'error':
1 failing
1) users utils should hash a password:
TypeError: size must be a number >= 0
at Promise (api\paths\users\utils.js:24:12)
at Object.exports.hashPassword (api\paths\users\utils.js:14:10)
at Context.it (api\paths\users\utils.test.js:30:13)
Has anyone any idea why?
I am using mocha
with should
and developing on node
.
Upvotes: 0
Views: 410
Reputation: 1393
Thanks to pietrovismara that pointed me towards the solution.
The problem was that salt_length
was a string and not a number. I was printing out the arguments and I could see they were 'correct' but obviously not the right Type (hence TypeError, I guess...)
I keep the argument in a .env
file and I read them in using the dotenv
package which obviously read them as simple strings (as it should)... the reason why it was working when I was 'testing' the function from another file was that in that instance I was not using the arguments read from .env
, I have something like:
const salt_length = process.env.SALT_LENGTH || 128;
Mocha was correclty using .env
values (strings), but when fooling around with the file I was not loading those enviroment variables.
I learned something today, that is I should go home when tired instead of charging on and not seeing things in front of my eyes.
Also, since mocha
supports promises, the 'correct' test case should be (using should
):
describe('users', () => {
describe('utils', () => {
it('should hash a password', () => {
return utils.hashPassword('secret').should.be.fulfilled();
});
});
});
Upvotes: 1