简体   繁体   English

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

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

I have a file config.js with the below code in it: 我有一个config.js文件,其中包含以下代码:

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

I have another file bus.js with the below code in it: 我还有另一个文件bus.js,其中包含以下代码:

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

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

Now, I want to unit test the file bus.js 现在,我要对文件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();
        });
});

Any Suggestions or help... 任何建议或帮助...

You need to require your module like this var config=require('./config.js'); 您需要像这样的模块要求var config=require('./config.js'); .

Edit: You should change your require call to the above. 编辑:您应该将您的require调用更改为上述内容。 Even if it works when you proxy as ('config.js') it won't work in real life. 即使当您以('config.js')代理身份运行时,它也无法在现实生活中运行。 Also you probably need to call bus the same way and build the config object as it is in the actual file. 同样,您可能需要以相同的方式调用bus并构建实际文件中的config对象。

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

It seems to me that you can do this in your test file: 在我看来,您可以在测试文件中执行此操作:

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