nodejs sinon如何从一个类中取消内联需要对象

时间:2018-05-01 04:43:47

标签: node.js unit-testing sinon stub stubbing

我正在尝试存在一个在内联需求行中执行某些操作的类。例如,这里可以说我正在为abc-handler.js编写单元测试,这取决于query-helperlogger。另一方面,query-helper也取决于logger。但是,我无法找到一种正确的方法来处理存根记录器并将其注入相关的依赖项。

以下是我的一些示例课程。

查询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;

以下是单元测试的示例块。这里abcHandler创建了./log目录,这个目录不应该发生,因为我正在传递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});

谢谢!

1 个答案:

答案 0 :(得分:0)

我用proxyquire解决了这个初始化noCallThru()

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

在此解释https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency