Skip to content

Instantly share code, notes, and snippets.

@kpdecker
Created February 4, 2016 18:18
Show Gist options
  • Save kpdecker/baad1f9266e2337b38d9 to your computer and use it in GitHub Desktop.
Save kpdecker/baad1f9266e2337b38d9 to your computer and use it in GitHub Desktop.
/* global document */
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import shallowUtils from 'react-shallow-testutils';
it.browser = function(name, fn) {
if (typeof document !== 'undefined') {
it(name, fn);
}
};
it.browser.only = function(name, fn) {
if (typeof document !== 'undefined') {
it.only(name, fn);
} else {
it.only(name);
}
};
export function renderToDOM(View, ...props) {
let node = document.createElement('div');
return props.reduce((prev, props) => {
return ReactDOM.render(<View {...props} />, node);
}, undefined);
}
export function renderWithContext(child, context) {
let childContextTypes = {};
Object.keys(context).forEach((key) => {
childContextTypes[key] = React.PropTypes.any;
});
class Host extends React.Component {
static childContextTypes = childContextTypes;
getChildContext() {
return context;
}
render() {
return this.props.children; // eslint-disable-line
}
}
return TestUtils.renderIntoDocument(<Host>{child}</Host>);
}
export function shallowRender(View, ...props) {
return shallowRenderWithContext(View, undefined, ...props);
}
export function shallowRenderWithContext(View, context, ...props) {
let renderer = TestUtils.createRenderer();
if (!props.length) {
props = [undefined];
}
props.forEach((props) => renderer.render(<View {...props} />, context));
return renderer.getRenderOutput();
}
export function findWithType(component, type) {
if (component._reactInternalInstance) {
if (typeof type === 'string') {
return TestUtils.findRenderedDOMComponentWithTag(component, type);
} else {
return TestUtils.findRenderedComponentWithType(component, type);
}
} else {
return shallowUtils.findWithType(component, type);
}
}
export function findAllWithType(component, type) {
if (component._reactInternalInstance) {
if (typeof type === 'string') {
return TestUtils.scryRenderedDOMComponentsWithTag(component, type);
} else {
return TestUtils.scryRenderedComponentsWithType(component, type);
}
} else {
return shallowUtils.findAllWithType(component, type);
}
}
export function findWithClass(component, clazz) {
if (component._reactInternalInstance) {
return TestUtils.findRenderedDOMComponentWithClass(component, clazz);
} else {
return shallowUtils.findWithClass(component, clazz);
}
}
export function findAllWithClass(component, clazz) {
if (component._reactInternalInstance) {
return TestUtils.scryRenderedDOMComponentsWithClass(component, clazz);
} else {
return shallowUtils.findAllWithClass(component, clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment