Skip to main content

Get innerHTML of Enzyme wrapper

In Enzyme, wrapper’s have a handle .html() method that will return the outerHTML for that element in the tree. It’s handy in the rare instance when the markup that your code outputs needs to be precise. You can read more about in the documentation.

However, there isn’t a method that returns the innerHTML. A use case I came across for this was caring about the children of an element, but not caring about the element itself. I didn’t want this test to fail if I needed to add an attribute to the parent element, only if the children changed.

So I wrote this little helper function to grab the innerHTML of a shallow wrapper in Enzyme:

function getInnerHTML(node) {
    return node.children().reduce((string, node) => {
        // A text node's html method doesn't return
        // anything, so we use text instead.
        return string + node.html() || node.text()
    }, '')
}

There might be other strategies using some of Enzyme’s built-in methods like .reduce() or .forEach(), so let me know if you come up with a better alternative.

Happy testing!



About the author

Sean McPherson is a software engineer for Khan Academy who specializes in web and mobile app development. He lives with his wife, sons, and dog in Pittsburgh, PA.