如何在Node JS中对嵌套函数进行单元测试?

时间:2019-04-01 06:03:55

标签: node.js mocha sinon chai

我有一个要为其编写单元测试的函数,但该函数正在调用另一个函数,因此我无法对该函数进行模拟/存根。

例如:

function getValue( param1, param2, callback){
    getData(param1, param3).then( response) => {
         return callback();
    }, (err) => {
         return callback();
    });
}

所以我不知道如何模拟getData()函数。

2 个答案:

答案 0 :(得分:1)

这是一个有效的示例,演示您正在尝试做的事情:

lib.js

function getData(param1, param2) {
  return fetch('someUrl');  // <= something that returns a Promise
}

exports.getData = getData;

code.js

const lib = require('./lib');

export function getValue(param1, param2, callback) {
  return lib.getData(param1, param2).then(response => {
    callback(response);
  }).catch(err => {
    callback(err);
  });
}

exports.getValue = getValue;

code.test.js

const sinon = require('sinon');

const lib = require('./lib');
const { getValue } = require('./code');

describe('getValue', () => {
  it('should do something', async () => {
    const stub = sinon.stub(lib, 'getData');
    stub.resolves('mocked response');

    const callback = sinon.spy();
    await getValue('val1', 'val2', callback);

    sinon.assert.calledWithExactly(stub, 'val1', 'val2');  // Success!
    sinon.assert.calledWithExactly(callback, 'mocked response');  // Success!
  });
});

更新

在注释中添加了他们不能使用async / await的OP,并且正在使用module.exports = getData;导出函数。

在这种情况下,模块导出函数,整个模块需要使用proxyquire之类的东西来模拟。

断言应在then回调中完成,测试应返回结果Promise,以便mocha知道等待它解决。

更新示例:

lib.js

function getData(param1, param2) {
  return fetch('someUrl');  // <= something that returns a Promise
}

module.exports = getData;

code.js

const getData = require('./lib');

function getValue(param1, param2, callback) {
  return getData(param1, param2).then(response => {
    callback(response);
  }).catch(err => {
    callback(err);
  });
}

module.exports = getValue;

code.test.js

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('getValue', () => {
  it('should do something', () => {
    const stub = sinon.stub();
    stub.resolves('mocked response');

    const getValue = proxyquire('./code', { './lib': stub });

    const callback = sinon.spy();
    return getValue('val1', 'val2', callback).then(() => {
      sinon.assert.calledWithExactly(stub, 'val1', 'val2');  // Success!
      sinon.assert.calledWithExactly(callback, 'mocked response');  // Success!
    });
  });
});

答案 1 :(得分:0)

function getValue( param1, param2, callback){
    getData(param1, param3).then( response) => {
         callback(response);
    });
}

getvalue(param1, param2, function(error, response)) {
   console.log(response)
}

这可能会对您有所帮助。

相关问题