Skip to content

Instantly share code, notes, and snippets.

@OscarGodson
Created August 26, 2014 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OscarGodson/0f9d78e91415cd2e34f6 to your computer and use it in GitHub Desktop.
Save OscarGodson/0f9d78e91415cd2e34f6 to your computer and use it in GitHub Desktop.
var Foo = require('../foo/index.js');
var someClass = new SomeClass({
someMethod: function () {
// How do I stub this without requiring it to be set on the prototype?
// ex: w/o having it set on someClass.baz = Foo.bar();
var baz = Foo.bar();
if (baz == 'hello') {
return 1
}
else {
return 0
}
}
});
@OscarGodson
Copy link
Author

Main issue is that the require is already "compiled" by the time it gets to the tests (otherwise the tests wouldnt run) so I can't really overwrite require() even

@jmreidy
Copy link

jmreidy commented Aug 26, 2014

OK, if the issue is stubbing something internally required by another module, then you'll need proxyquireify, a browserify-specific version of proxyquire.

That'd let you do something like:

var SomeClassStub = Sinon.stub();
var Foo = proxyquire('../foo/index.js', { './someClass': SomeClassStub });

So now, internal to the Foo module, the require to ./someClass will resolve to your stub. Hooray. All the power of Jest with the flexibility of Sinon - and it works in the browser too!

Here's an example of not-real test code with Browserify, Mocha, Sinon running in a Karma harness: https://github.com/jmreidy/react-combobox/blob/master/test/combobox.test.js. Main code:

var proxyquire = require('proxyquireify')(require);
describe('Combobox', function () {
  var instance, stubOption;
  beforeEach(function () {
    stubOption = sinon.stub();
    instance=proxyquire('../lib/combobox', {
      './option': stubOption
    });
  });

Presumably proxyquireify would work anywhere you're successfully packaging Browserify bundled code/tests. (So Jasmine should be fine.)

@jmreidy
Copy link

jmreidy commented Aug 26, 2014

Note that the karma example above is relying on a key karma plugin, or at least my fork of it: https://github.com/jmreidy/karma-browserifast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment