为下面的函数 node.js 编写单元测试用例

时间:2021-03-15 10:53:18

标签: javascript node.js unit-testing testing mocha.js

我创建了一个函数,需要对其进行测试 文件 name-abc.js

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

文件名-abc_test.js

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

在调用这个函数时我应该传递什么参数以及我应该断言什么值。

1 个答案:

答案 0 :(得分:0)

您可以使用 Node.js 的 assert 作为断言库。并且,为 callback 函数创建一个模拟或存根,将它传递到 obj.a() 方法中。最后,断言是否要使用正确的参数调用 callback 函数。

例如

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');
  });
});

单元测试结果:

  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 |                   
-------------|---------|----------|---------|---------|-------------------