简体   繁体   中英

Write Unit test case for below function- node.js

I have created a function and need to test it File name-abc.js :

a: function (cb) {
  return function (err, res) {
    if (err) return cb(err);
    return cb(null, res);
  };
},

File name-abc_test.js

describe('test function,()=>{
    it('test',(done)=>{
      // HOW TO TEST THE ABOVE FUNCTION.. WHAT ARGUMENTS SHOULD BE PASSES AS CALLBACK 
      })
    })

What arguments should i pass while calling this function and on what values should i assert on.

You can use assert of Node.js as your assertion library. And, create a mock or stub for the callback function, pass it in obj.a() method. At the end, assert that if the callback function is to be called with correct parameters.

Eg

name-abc.js :

const obj = {
  a: function (cb) {
    return function (err, res) {
      if (err) return cb(err);
      return cb(null, res);
    };
  },
};

module.exports = obj;

name-abc.test.js :

const obj = require('./name-abc');
const assert = require('assert');

describe('66636577', () => {
  it('should handle error', () => {
    const callArgs = [];
    const mCallback = (err, res) => {
      callArgs.push([err, res]);
    };
    const mError = new Error('network');
    obj.a(mCallback)(mError);
    assert(callArgs[0][0] === mError && callArgs[0][1] === undefined, 'expect callback to be called with error');
  });

  it('should success', () => {
    const callArgs = [];
    const mCallback = (err, res) => {
      callArgs.push([err, res]);
    };
    const mRes = 'teresa teng';
    obj.a(mCallback)(null, mRes);
    assert(callArgs[0][0] === null && callArgs[0][1] === 'teresa teng', 'expect callback to be called with response');
  });
});

unit test result:

  66636577
    ✓ should handle error
    ✓ should success


  2 passing (4ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 name-abc.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