jonsanders101
jonsanders101

Reputation: 525

Proxyquire does not stub

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

} 
}

Upvotes: 0

Views: 1024

Answers (1)

HMR
HMR

Reputation: 39270

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");
    } 
  )
});

Upvotes: 1

Related Questions