Skip to content

Instantly share code, notes, and snippets.

@nikgraf
Created December 18, 2015 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikgraf/3b5f4fef088ab4a3a7be to your computer and use it in GitHub Desktop.
Save nikgraf/3b5f4fef088ab4a3a7be to your computer and use it in GitHub Desktop.
Chai React Shallow Testing
import {findAll} from 'react-shallow-testutils';
import objectMatches from 'object-matches';
import inspectReactElement from 'inspect-react-element';
const findAllMatching = (rootElementTree, elementTreeToMatch) => {
return findAll(rootElementTree, (element) => {
// In case a null is passed for a template value
if (element === null) return false;
const matchType = (elementTreeToMatch.type ? element.type === elementTreeToMatch.type : true);
const matchSubsetOfProps = objectMatches(element.props, elementTreeToMatch.props);
return matchType && matchSubsetOfProps;
});
};
const addIndentToLines = (text) => {
const lines = text.split('\n');
const indentedLines = lines.map((line) => {
return ` ${line}`;
});
return indentedLines.join('\n');
};
module.exports = (chai) => {
const Assertion = chai.Assertion;
Assertion.addMethod('containElements', function containTree(elementTreeToMatch) {
const rootElementTree = this._obj;
const foundElements = findAllMatching(rootElementTree, elementTreeToMatch);
if (foundElements.length < 1) {
const rootTree = addIndentToLines(inspectReactElement(rootElementTree));
const matchTree = addIndentToLines(inspectReactElement(elementTreeToMatch));
throw new Error(
`expected
${rootTree}
to contain
${matchTree}
`
);
}
});
};
import TestUtils from 'react-addons-test-utils';
export default (elements) => {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(elements);
return shallowRenderer.getRenderOutput();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment