简体   繁体   English

模块中的单元测试功能

[英]unit-testing functions in module

Ok, I'm making a serious stab at learning about unit testing for the first time, I'm using Mocha & Sinon. 好的,我是第一次使用Mocha&Sinon认真学习单元测试。

So hypothetical dumb module, contains functions foo and bar . 因此,假设的哑模块包含函数foobar Foo depends on bar . Foo取决于bar

(function() {

  var bar = function(callback) {
    if (willOfTheGods) {
      callback('err', null);
    } else
      callback(null, 'hurrah');
  }

  var foo = function() {

    bar(function(err, res) {
      //blah deh blah
    });
  }

  module.exports = {
    bar: bar,
    foo: foo
  }

})();

I want to stub bar so I can test foo . 我想对bar进行存根以便可以测试foo

This seems logical from the Sinon docs ... 从Sinon文档看来这是合乎逻辑的...

var myModule = require('../myModule');
sinon.stub(myModule, 'bar')
myModule.bar.callsArgWith(0, ['err', null]);

but it only works if I call bar in the test itself. 但仅当我在测试本身中调用bar ,它才有效。

myModule.bar(function(err, result){
  console.log('err, result');
});

When I call myModule.foo it still uses the original 'unstubbed one'. 当我调用myModule.foo它仍然使用原始的“未插入的”。

It seems like creating a stub just creates a new local variable for that function rather than stubbing it in the module. 似乎创建存根只是为该函数创建一个新的局部变量,而不是在模块中存根。

Or am I missing something completely - or just doing the wrong thing? 还是我完全错过了某些东西-或者只是做错了什么?

Ok, Some research revealed that stubbing like this is only replacing the value of the module.exports property not the underlying function. 好的,一些研究表明,像这样的存根只是替换了module.exports属性的值,而不是底层函数。 So I need to use something like rewire to actually get inside the module. 因此,我需要使用诸如rewire之类的东西才能真正进入模块内部。

So now if I drop the Sinon stub and just do: 因此,现在,如果我放弃Sinon存根并执行以下操作:

var myModule = rewire('../myModule');

myModule.__set__('bar', function(callback){
  callback('err', null);
});

it works ... kind of. 它的工作原理 It only works if I remove the self executing function wrapping from myModule, ie remove (function(){ ... })(); 仅当我从myModule中删除自动执行的函数包装(function(){ ... })();即remove (function(){ ... })(); . My understanding was that was a best-practice ... but maybe only in the browser? 我的理解是,这是一种最佳实践……但可能仅在浏览器中? Whole different question there I guess. 我猜整个问题都在那里。

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

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