Created
December 18, 2015 07:37
-
-
Save nikgraf/3b5f4fef088ab4a3a7be to your computer and use it in GitHub Desktop.
Chai React Shallow Testing
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 {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} | |
` | |
); | |
} | |
}); | |
}; |
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 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