Search code examples
node.jsunit-testingsinonstubstubbing

nodejs sinon how to stub inline require object from a class


I am trying to stub a class which does some stuff at inline require line. For example here lets say I am writing a unit test for abc-handler.js which depends on query-helper and logger. On the other hand, query-helper also depends on logger. However, I couldn't find a proper way to deal with stubbing logger and injecting it into related dependencies.

Here is some sample classes I have.

query-helper.js

var logger = require('./log/logger.js').getDefaultLogger();

class QueryHelper {
  static save() {
    // save stuff
  }
}

abc-handler.js

const logger = require('./log/logger.js').getDefaultLogger();
const QueryHelper = require('./query-helper.js');
var Handler = require('./handler.js');

/**
    Handler for 'binance' exchange
*/
class ABCHandler extends Handler {
    constructor(params) {
        super(params);
    }

    doStuff() {}
}

logger.js

var Log = require('log');
var fs = require('fs');
var dir = './logs';
const config = require('./config.js');
class LoggerFactory {
    static getDefaultLogger() {
        this._createDir();
        if (this.logger === null || this.logger === undefined) {
            this.logger = new Logger("application");
        }
        return this.logger;
    }

    static _createDir() {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
    }
}

class Logger {
    constructor(operationType) {
        this.logger = new Log("debug", fs.createWriteStream("logs/" + operationType + ".log"), {flags: "a"});
    }
}

module.exports = LoggerFactory;

Here is the example block from unit-test. Here abcHandler creates ./log directory which shouldn't happen because I am passing loggerStub

var sinon = require('sinon');
var proxyquire = require('proxyquire');
var Log = require('log');
...

logger = proxyquire('./logger.js', {'./config.js': config});
loggerStub = sinon.createStubInstance(Log);
_createDirStub = sinon.stub(logger, "getDefaultLogger").returns(loggerStub);

queryHelper = proxyquire('./query-helper.js' , {'./logger.js': logger});
queryHelperGetLastDataStub = sinon.stub(queryHelper, "save");

abcHandler = proxyquire('.abc-handler.js'
                                    , {'./logger.js': logger,
                                        './query-helper.js': queryHelper,
                                        './config.js': config});

Thanks!


Solution

  • I solved this initializing proxyquire with noCallThru().

    var proxyquire = require('proxyquire').noCallThru();
    

    explained here https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency