Prajwal
Prajwal

Reputation: 321

How to stub object's property, not method?

I have a file config.js with the below code in it:

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

I have another file bus.js with the below code in it:

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

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...

Upvotes: 0

Views: 650

Answers (2)

robertklep
robertklep

Reputation: 203494

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();
    });
  });

});

Upvotes: 2

Brian Baker
Brian Baker

Reputation: 996

You need to require your module like this var config=require('./config.js');.

Edit: You should change your require call to the above. Even if it works when you proxy as ('config.js') it won't work in real life. Also you probably need to call bus the same way and build the config object as it is in the actual file.

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

Upvotes: 1

Related Questions