Skip to content

Instantly share code, notes, and snippets.

@bregenspan
Last active December 17, 2020 02:17
Show Gist options
  • Save bregenspan/83126a50da7cf0a4d16b11499e12f7bc to your computer and use it in GitHub Desktop.
Save bregenspan/83126a50da7cf0a4d16b11499e12f7bc to your computer and use it in GitHub Desktop.
Recursively dive() to deeply-wrapped components via Enzyme
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 });
}
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);
@miriyalee
Copy link

I think you should add instance && to line 21.
const context = merge({}, instance && instance.getChildContext ? instance.getChildContext() : {},

@The-Code-Monkey
Copy link

Hi on this what does merge relate to as it doesn't specify

@bregenspan
Copy link
Author

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