0

I'm trying to use proxyquire to stub the spawnSync method of the child_process module, but it doesn't work. The console.log(gitResponse) in my index.js file doesn't return the stubbed string, but the unstubbed response (in this case, the git help text).

Can someone see what I am doing wrong?

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

} 
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
jonsanders101
  • 525
  • 1
  • 6
  • 13

1 Answers1

1

According to the documentation; should you not be doing something like this:?

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");
    } 
  )
});
HMR
  • 37,593
  • 24
  • 91
  • 160
  • I define an object called `const myStub = {}` in the initial describe block and then I add the functions I want to stub to `myStub` as needed in each test `myStub.someFunc = () => 1`. Immediately afterward I define my lib to test `let lib = proxyquire('mylib', {'./required-by-lib': myStub})`. The docs were not clear to me that the examples are within individual tests. – Todd Jan 08 '19 at 15:35