Skip to content

Instantly share code, notes, and snippets.

@mars mars/rewire-module.js
Last active Sep 15, 2016

Embed
What would you like to do?
Manually mock React components; Jasmine helper to stub & teardown a bunch of a module's dependencies with Rewire. How-to: http://substantial.com/blog/2014/11/11/test-driven-react-how-to-manually-mock-components/
/*
Jasmine helper to stub & teardown a bunch of a module's dependencies.
describe("SomeModule", function() {
var SomeModule = rewire("some-module");
rewireModule(SomeComponent, {
ItsComponent: React.createFactory('div'),
AnotherComponent: React.createFactory('div')
});
it("yadda yadda", function() {
});
});
Rewire's resolver does not honor Webpack config.resolve.alias, so pass
the already-rewired module.
*/
var rewireModule = function rewireModule(rewiredModule, varValues) {
var rewiredReverts = [];
beforeEach(function() {
var key, value, revert;
for (key in varValues) {
if (varValues.hasOwnProperty(key)) {
value = varValues[key];
revert = rewiredModule.__set__(key, value);
rewiredReverts.push(revert);
}
}
});
afterEach(function() {
rewiredReverts.forEach(function(revert) {
revert();
});
});
return rewiredModule;
};
@azaharakis

This comment has been minimized.

Copy link

azaharakis commented Feb 16, 2015

Hi I was reading your blog article and came across this gist.
I was interested in using this technique to stub out subcomponents, basically a test that my parent component creates an instance of subcomponent and verify it with scryRenderedComponentsWithType, however this seems to miss the mark for me, as it completely overrides the subcomponent with a new stub and cannot actually verify that the subcomponent was called from the actual commonJS module.
Thanks for the blog post, has been quite helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.