Skip to content

Instantly share code, notes, and snippets.

@mjackson
Last active January 29, 2020 22:42
Show Gist options
  • Save mjackson/c90a84d94723a68cfeebb9d83aa759c2 to your computer and use it in GitHub Desktop.
Save mjackson/c90a84d94723a68cfeebb9d83aa759c2 to your computer and use it in GitHub Desktop.
expect.extend({
toContainElement(instance, targetElement) {
let matchingElements = instance.findAllByProps(targetElement.props);
if (matchingElements.length === 0) {
return {
message() {
let props = JSON.stringify(targetElement.props);
return `expected to find element with props ${props}`;
},
pass: false
};
}
let matchedElement = matchingElements.find(
element => element.type === targetElement.type
);
if (matchedElement == null) {
return {
message() {
let type = targetElement.type.displayName || targetElement.type.name;
return `expected to find element with type ${type}`;
},
pass: false
};
}
return {
message() {
let type = targetElement.type.displayName || targetElement.type.name;
return `expected not to find element with type ${type}`;
},
pass: true
};
}
});
// use it like:
import { create } from 'react-test-renderer';
let renderer = create(<div>hi</div>);
expect(renderer.root).toContainElement(<div>hi</div>);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment