Skip to content

Instantly share code, notes, and snippets.

@localnerve
Last active August 29, 2015 14:16
Show Gist options
  • Save localnerve/31b77ad56da309fa9d97 to your computer and use it in GitHub Desktop.
Save localnerve/31b77ad56da309fa9d97 to your computer and use it in GitHub Desktop.
jsDom React Testing - getMarkupWrap - Markup wrapping node not initialized. A friendly module-monkey-patch and module-state reminder courtesy of React.
/*
While debugging using jsdom with react tests, I reminded myself of "when" module code executes.
In doing so, I also reminded myself how to monkey patch loaded modules.
Happy remembering!
*/
beforeEach(function() {
// setup jsdom
testDom();
// tell react DOM is usable
require('react/lib/ExecutionEnvironment').canUseDOM = !!document;
});
/**
* Test body debugging.
* It reminded me that even though I set canUseDOM in the beforeEach,
* dummyNode (the value in getMarkupWrap module state) had already been taken in getMarkupWrap at load time.
*/
it('some test with debug code in it', function() {
// @@@ debug-start
var getMarkupWrapOrig = require('react/lib/getMarkupWrap');
function getMarkupWrap(nodeName) {
// canUseDOM was set to true in beforeEach after jsdom setup success
console.log('@@@ canUseDOM = '+require('react/lib/ExecutionEnvironment').canUseDOM);
// this is a real HTMLDivElement
console.log('@@@ div result = '+document.createElement('div'));
getMarkupWrapOrig(nodeName);
}
// replace cached, loaded module exports, could've monkey patched individuals...
require.cache[require.resolve('react/lib/getMarkupWrap')] = {
exports: getMarkupWrap
};
// This still gets dummyNode === null, even though canUseDOM was corrected after the fact.
// (to fix, you'll have to reload getMarkupWrap entirely with the new canUseDOM to get dummyNode set correctly)
var wrap = require('react/lib/getMarkupWrap')('*');
// never executes:
console.log('@@@ wrapped = '+wrap);
// @@@ debug-end
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment