简体   繁体   中英

mock a function in nodejs using mocha

I'm writing unit test cases for my node application using mocha on very first time. I have no clear idea about how to mock a function in mocha.

I added the function of my node application. How can a unit test for below mentioned function look like?.

var authHandler = require('./authenticationHandler');

exports.postloginValues = (req, res) => {

  var realEdUsername_Update = req.body.uName;
  var encodedPassword = Buffer.from(req.body.password).toString('base64');

  var jsonData = {
    loginName : realEdUsername_Update,
    userPassword : encodedPassword
  };

  var parseData = JSON.stringify(jsonData);

  var result = authHandler.validateRealEdUser(parseData, res);
};

index.js :

var authHandler = require('./authenticationHandler');

exports.postloginValues = (req, res) => {
  var realEdUsername_Update = req.body.uName;
  var encodedPassword = Buffer.from(req.body.password).toString('base64');

  var jsonData = {
    loginName: realEdUsername_Update,
    userPassword: encodedPassword,
  };

  var parseData = JSON.stringify(jsonData);

  var result = authHandler.validateRealEdUser(parseData, res);
};

authenticationHandler.js :

module.exports = {
  validateRealEdUser(parseData, res) {},
};

index.test.js :

const { postloginValues } = require('./');
var authHandler = require('./authenticationHandler');
const sinon = require('sinon');

describe('60734436', () => {
  it('should pass', () => {
    const validateRealEdUserStub = sinon.stub(authHandler, 'validateRealEdUser');
    const mReq = { body: { password: '123', uName: 'james' } };
    const mRes = {};
    postloginValues(mReq, mRes);
    sinon.assert.calledWithExactly(
      validateRealEdUserStub,
      JSON.stringify({ loginName: 'james', userPassword: Buffer.from(mReq.body.password).toString('base64') }),
      mRes,
    );
    validateRealEdUserStub.reset();
  });
});

unit test results with coverage report:

  60734436
    ✓ should pass


  1 passing (8ms)

--------------------------|---------|----------|---------|---------|-------------------
File                      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------------------|---------|----------|---------|---------|-------------------
All files                 |     100 |      100 |      50 |     100 |                   
 authenticationHandler.js |     100 |      100 |       0 |     100 |                   
 index.js                 |     100 |      100 |     100 |     100 |                   
--------------------------|---------|----------|---------|---------|-------------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM