繁体   English   中英

如何存根对象的属性而不是方法?

[英]How to stub object's property, not method?

我有一个config.js文件,其中包含以下代码:

module.exports:
{
   development: {
        switch: false
        }
}

我还有另一个文件bus.js,其中包含以下代码:

var config=require('config.js');

getBusiness:function(req,callback){
         if(config.switch) {
                  // Do something
         }else{
                 // Do something else
         }
}

现在,我要对文件bus.js进行单元测试

require('mocha');

var chai = require('chai'),
      expect = chai.expect,
      proxyquire = require('proxyquire');

var bus = proxyquire('bus.js', {
                 'config':{
                        switch:true
                  }
});

describe('Unit Test', function() {

        it('should stub the config.switch', function(done) {
            bus.getBusiness(req, function(data) {
              // It should stub the config.switch with true not false and give code coverage for if-else statmt. 
            });
           done();
        });
});

任何建议或帮助...

您需要像这样的模块要求var config=require('./config.js');

编辑:您应该将您的require调用更改为上述内容。 即使当您以('config.js')代理身份运行时,它也无法在现实生活中运行。 同样,您可能需要以相同的方式调用bus并构建实际文件中的config对象。

var bus = proxyquire('./bus.js', {
             './config':{
                 development: {                   
                    switch:true
                 }
              }
});

在我看来,您可以在测试文件中执行此操作:

var chai   = require('chai'),
  expect   = chai.expect;
var config = require('./config');

describe('Unit Test', function() {

  it('should stub the config.switch', function(done) {
    config.development.switch = true;
    bus.getBusiness(req, function(data) {
      ...
      done();
    });
  });

});

暂无
暂无

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

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