Last active
September 22, 2015 17:59
-
-
Save insin/9005207 to your computer and use it in GitHub Desktop.
Custom QUnit assertion against generated HTML for contents created with React.DOM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Custom assertion for contents created with React.DOM. | |
*/ | |
var reactHTMLEqual = (function() { | |
var reactAttrs = / data-react[-\w]+="[^"]+"/g | |
var wrapperElement = /^<div>|<\/div>$/g | |
return function reactHTMLEqual(component, expectedHTML, message) { | |
// Some components just need to return content strings | |
if (typeof component == 'string') { | |
return strictEqual(component, expectedHTML, message) | |
} | |
// If a component renders to an Array it needs to be wrapped with another | |
// element for rendering. | |
var wrapped = false | |
if (Array.isArray(component)) { | |
component = React.DOM.div(null, component) | |
wrapped = true | |
} | |
// If a component is using the "ref" attribute, it needs to be rendered | |
// within a render() method, in which case a function which does the | |
// rendering should be passsed. | |
if (typeof component == 'function') { | |
var renderFunc = component | |
var reactClass = React.createClass({ | |
render: function() { | |
var rendered = renderFunc() | |
if (Array.isArray(rendered)) { | |
rendered = React.DOM.div(null, rendered) | |
wrapped = true | |
} | |
return rendered | |
} | |
}) | |
component = reactClass() | |
} | |
stop() | |
try { | |
React.renderComponentToString(component, function(html) { | |
html = html.replace(reactAttrs, '') | |
// Remove HTML for any wrapper element which was added | |
if (wrapped) { | |
html = html.replace(wrapperElement, '') | |
} | |
equal(html, expectedHTML, message) | |
}) | |
} | |
catch (e) { | |
// React is throwing these when rendering to String(!?) | |
if (e.message !== "Cannot read property 'firstChild' of undefined" && | |
e.message !== "ancestorNode is undefined") { | |
throw e | |
} | |
} | |
finally { | |
start() | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment