Last active
December 17, 2020 02:17
-
-
Save bregenspan/83126a50da7cf0a4d16b11499e12f7bc to your computer and use it in GitHub Desktop.
Recursively dive() to deeply-wrapped components via Enzyme
This file contains 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
import merge from 'lodash/merge'; | |
/** | |
* Given an Enzyme ShallowWrapper and component identifier, dives() down until the | |
* specified component is the root component. | |
* | |
* @param { Enzyme.ShallowWrapper } shallowWrapper - wrapper to dive into | |
* @param { string } name of component to dive for (should match constructor name). | |
* @param { object= } options to pass to dive() | |
*/ | |
function diveTo(shallowWrapper, identifier, options = { context: {} }) { | |
const element = shallowWrapper.getElement(); | |
if (!(element && element.type)) { | |
throw new Error(`Failed to dive to ${identifier} - is it not in the component tree?`); | |
} | |
const instance = shallowWrapper.instance(); | |
if (instance && instance.constructor.name === identifier) { | |
return shallowWrapper; // We found it! | |
} | |
// Enzyme limitation workaround: until https://github.com/airbnb/enzyme/issues/664 is resolved, | |
// it's necessary to manually pass down child context like this | |
const context = merge({}, instance && instance.getChildContext ? instance.getChildContext() : {}, | |
options.context); | |
return diveTo(shallowWrapper.dive({ context }), identifier, { context }); | |
} |
This file contains 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
import { shallow } from 'enzyme'; | |
const mountOptions = {}; | |
const componentTree = /* Some JSX here, where <ComponentUnderTest> is deeply nested in HOCs... */; | |
const componentUnderTest = diveTo(shallow(componentTree, mountOptions), 'ComponentUnderTest', mountOptions); |
Hi on this what does merge relate to as it doesn't specify
Oops, sorry - I think it assumed "merge" had been imported from Lodash. I just switched example to Object.assign, but actually a deep merge is probably needed, so switching back but making it clearer.
But I'd check if any of this is still needed in latest Enzyme, it's possible it's now unecessary!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi on this what does merge relate to as it doesn't specify