Search code examples
node.jsmocha.jssinon-chai

testing services in nodejs with sinon chai & mocha


i'm tring to test my bycrptSevice... here my service:

module.exports = (bcrypt) => {
  const hashKey = Number(process.env.BCRYPT_HASH_KEY) || 10;

  function checkPassword(reqPassword, userPassword) {
    console.log("bycrptService: checkPassword call()");

    return bcrypt.compareSync(reqPassword, userPassword);
  }

  function createHashPassword(password) {
    console.log("bycrptService: createHashPassword call()");

    return bcrypt.hashSync(password, hashKey);
  }

  return {
    checkPassword,
    createHashPassword
  };
}

this is the test file:

const { assert, should, expect, sinon } = require('../baseTest');

const bcryptService = require('../../services/bcryptService');
const bcryptjs = require('bcryptjs');

describe('bcryptService Tests', function() {
    const bcrypt = bcryptService(bcryptjs);
    let Password = '1234';
    let crptPassword = bcrypt.createHashPassword(Password);

    it('test the createHashPassword() create new hash password to the input password',function(){
      expect(crptPassword).to.not.be.equal(Password);
    })

    it('test the checkPassword() check if return true when its compere and false when its not', function() {
       bcrypt.checkPassword(Password,crptPassword).should.be.true;
       bcrypt.checkPassword('987',crptPassword).should.be.false;
    })
    it('test onInit bycrptSevice shoud have hashKey',function(){
     //how to check it??? 
    })
});

my first question is: how could i check if hashKey exist? secondly: shoud i test it? i mean - its my responsibility to check it or maybe i don't be care about privete field
thanks


Solution

  • In order to test the hashKey you must export it in your bycrptSevice and then you can do whatever tests you want to it.

    Regarding your second question, it depends, but for your case, the hashkey is an environment variable, and you should setup it before running your tests, so its not necessary to test it.