nodejs sinon 如何存根内联需要来自 class 的对象

nodejs sinon how to stub inline require object from a class

我正在尝试对一个 class 进行存根,它在内联 require 行中做一些事情。例如,假设我正在为 abc-handler.js 编写单元测试,它依赖于 query-helperlogger。另一方面,query-helper 也依赖于 logger。但是,我找不到合适的方法来处理存根记录器并将其注入相关依赖项。

这是我的一些示例 classes。

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

谢谢!

我用 noCallThru() 解决了初始化 proxyquire 的问题。

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

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