thlorenz / proxyquire

🔮 Proxies nodejs require in order to allow overriding dependencies during testing.
MIT License
2.75k stars 100 forks source link

Doubt about usage #111

Closed lazywithclass closed 8 years ago

lazywithclass commented 8 years ago

Hello, thanks for this library!

I am having a look at it if I can use it for a mutation testing tool I am writing. I am experimenting with the following setup:

// test.js
describe('fn', function() {

  var lib = require('./source'),
      expect = require('chai').expect;

  it('returns true', function() {
    expect(lib.fn()).to.be.true;
  });

});
// source.js
var lib = {};

lib.fn = function() {
  return true;
};

module.exports = lib;
// runner.js
var proxyquire = require('proxyquire');
proxyquire('./test', {
  './source': {
    fn: function() {
      console.log('proxyquire!');
    }
  }
});

var Mocha = require('mocha');
new Mocha().addFile('./test').run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

When running node runner.js I am getting

ReferenceError: describe is not defined

so I suppose something is happening, but I am probably doing something really silly here, do you see anything I might be missing? Any hint or help would be much appreciated, thanks.

bendrucker commented 8 years ago

Yeah unfortunately I'm pretty sure you really can't run Mocha tests without the Mocha executable. 99.9% sure that's the culprit here. The API you're using isn't documented (http://mochajs.org/#require) so I'm not even quite sure how they intend it to behave. Unfortunately my only recommendation is to use a test tool without global magic (e.g. tape) which is probably not what you wanted to hear.

lazywithclass commented 8 years ago

I got to that usage of Mocha after reading this https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically

I could possibly use that require way, but then it would mean writing to files, which is what I'm trying to avoid with this approach. Well, I'll have to dig deeper, thank you for your prompt answer nonetheless.

Cheers

bendrucker commented 8 years ago

Got it. Either way, Mocha's making the requires for you. The only thing you could try is setting @global = true on the value in stubs.fn so that Mocha's side effects (possibly) get a stubbed dep from the module cache.

lazywithclass commented 8 years ago

I didn't understand your suggestion, sorry, could you please give an example?

bendrucker commented 8 years ago
fn['@global'] = true

proxyquire('./test', {fn: fn})

function fn () {}
lazywithclass commented 8 years ago

Got it, thanks ;D