javascript - 如何 stub 对象的属性而不是方法?

标签 javascript unit-testing mocha.js chai proxyquire

我有一个文件 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 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();
    });
  });

});

关于javascript - 如何 stub 对象的属性而不是方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772533/

相关文章:

javascript - Node JS 和 pdfkit - addPage() 循环

javascript - 如何在不使用 jquery 的情况下在 javascript 中创建动态 div?

javascript - 如何将对象中的每个值写入文本文件中的每一行

javascript - 在 Controller 中使用警报脚本后返回 View

python - 如何在类的方法中模拟外部函数

java - 是否有用于运行测试组的 JUnit TestRunner?

javascript - 'mocha' 不被识别为内部或外部命令 - mocha 不会自动安装 supertest

javascript - 为什么在 karma 和 jasmine 中运行测试时 fs.readFile 不是一个函数?

javascript - 测试在 Mocha 中应该失败的东西。 (断言而不捕获)

javascript - 在 module.exports 方法上使用 sinon 测试方法调用