Skip to content

Instantly share code, notes, and snippets.

@mars
Last active September 15, 2016 08:51
Show Gist options
  • Save mars/f4ff063ac7dca5508534 to your computer and use it in GitHub Desktop.
Save mars/f4ff063ac7dca5508534 to your computer and use it in GitHub Desktop.
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
Copy link

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