如何在节点js中对嵌套函数进行单元测试?

问题描述 投票:0回答:2

我有一个函数,我正在编写单元测试但该函数正在调用另一个函数,在那里我无法模拟/存根该函数。

例如 :

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

所以我不知道如何模拟getData()功能。

node.js mocha sinon chai
2个回答
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!
  });
});

更新

OP在评论中添加了他们不能使用async / await并使用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!
    });
  });
});

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

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

它可能对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.