Skip to content

Instantly share code, notes, and snippets.

@man27382210
Forked from bregenspan/diveTo.js
Last active December 17, 2020 03:02
Show Gist options
  • Save man27382210/2ee8d29f5670ec070fd5e0cb044ca6cb to your computer and use it in GitHub Desktop.
Save man27382210/2ee8d29f5670ec070fd5e0cb044ca6cb 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 { ShallowWrapper } from 'enzyme';
type DiveToType = (shallowWrapper: ShallowWrapper, identifier: string) => ShallowWrapper;
const diveTo: DiveToType = (shallowWrapper: ShallowWrapper, identifier: string) => {
const element = shallowWrapper.getElement();
if (!(element && element.type)) {
throw new Error(`Failed to dive to ${identifier} - is it not in the component tree?`);
}
if (shallowWrapper.find(identifier).length > 0) {
return shallowWrapper;
}
return diveTo(shallowWrapper.dive(), identifier);
}
export default diveTo;
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment