繁体   English   中英

如何测试使用Mocha,Sinn和Chai返回的函数?

[英]How do I test a function which returns a function using Mocha, Sinon, and Chai?

我有一个函数,它返回另一个同名的函数。 在第二个函数内部,正在使用其他模块的函数。 我只想测试其他模块的功能是否被调用。

这是一些代码来阐明我的意思:

exports.getCache = function (model) {
  return function getCache (req, res){
     //some code
     key = utils.uniqueKey(model, id)
     //some code

     res.json(result);
  }
}

我想检查是否正在调用uniqueKey以及是否正在调用res.json。

感谢您的任何帮助,谢谢!

您可以简单地写:

sinon.spy(utils, 'uniqueKey')

在您的测试文件中,可能在beforeEach函数中。 然后,只要调用chai.expect函数就很容易检查它:

expect(utils.uniqueKey.called).to.be.true();  
expect(utils.uniqueKey.calledWith({modelValue: 'value'}, 'someId')).to.be.true(); 

其中{modelValue: 'value'}'someId'modelid变量的实际值。

要使组件可测试,必须使其依赖项可注入。 如我所见,您的代码取决于utils 要正确地模拟它,您不能只require('utils') ,而必须实现某种方式来连接依赖项。 使用一些DI库,或者只是扩展组件的公共接口:

var utils;

module.exports.dependencies = function (_utils) {
    utils = _utils;
};

module.exports.getCache = function (model) {
    key = utils.uniqueKey(model, id);
};

然后在生产代码中使用引导组件之前调用component.dependencies(require('utils')) 在测试用例中,您可以传递一个间谍: component.dependencies(spy);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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