【问题标题】:Proxyquire does not stubProxyquire 不存根
【发布时间】:2018-05-05 14:35:13
【问题描述】:

我正在尝试使用 proxyquire 来存根 child_process 模块的 spawnSync 方法,但它不起作用。我的 index.js 文件中的 console.log(gitResponse) 不返回存根字符串,而是返回未存根的响应(在本例中为 git 帮助文本)。

谁能看出我做错了什么?

/index.js

var childProcess = require('child_process');

function init () {
  var gitInit = childProcess.spawnSync('git', ['init']);
  var gitResponse = gitInit.stdout.toString() || gitInit.stderr.toString();
  console.log(gitResponse);
}

module.exports = {
init: init
}

/test/indexTest.js

var assert = require('assert');
var index = require('../index.js');
var sinon = require('sinon');
var proxyquire = require('proxyquire');

describe('test', function () {
it('tests', function () {

    var spawnSyncStub = function (command, args) {
        return {
          stdout: {
            toString: () => "git init success string"

          }
        };
      };

proxyquire('../index.js', {
        'child_process': {
          spawnSync: spawnSyncStub
        }
      });

index.init();

} 
}

【问题讨论】:

    标签: javascript node.js proxyquire


    【解决方案1】:

    根据documentation;你不应该这样做吗:?

    var assert = require('assert');
    
    
    var index = proxyquire('../index.js', {
      'child_process': {
        spawnSync: function (command, args) {
          return {
            stdout: {
              toString: () => "git init success string"
            }
          };
        }
      }
    });
    
    var sinon = require('sinon');
    var proxyquire = require('proxyquire');
    
    describe('test', function () {
      it(
        'tests'
        ,function () {
          sinon.assert.match(index.init(), "git init success string");
        } 
      )
    });
    

    【讨论】:

    • 我在初始描述块中定义了一个名为const myStub = {} 的对象,然后根据每个测试myStub.someFunc = () => 1 的需要,将我想要存根的函数添加到myStub。紧接着我定义了我的库来测试let lib = proxyquire('mylib', {'./required-by-lib': myStub})。我不清楚这些文档是否在单独的测试中。
    猜你喜欢
    • 2015-07-08
    • 2017-01-27
    • 2017-12-23
    • 2019-08-18
    • 2017-01-16
    • 2021-09-23
    • 2018-08-12
    • 2017-07-21
    相关资源
    最近更新 更多