Skip to content

Instantly share code, notes, and snippets.

@sbaechler
Last active February 20, 2020 22:16
Show Gist options
  • Save sbaechler/9678286acfe18c7732e5d3adad5b9dda to your computer and use it in GitHub Desktop.
Save sbaechler/9678286acfe18c7732e5d3adad5b9dda to your computer and use it in GitHub Desktop.
Enzyme (Jest) helper: Creates a HTML context for testing elements that contain a DOM reference (e.g. getElementById) such as the Reactstrap Tooltip.
/**
* Creates a HTML context for testing elements that require a DOM
* such as the Tooltip.
*
* @returns A tuple with the DOM container and a cleanup function.
*
* @example
* ```typescript
* let container: HTMLElement;
* let cleanup: () => void;
* beforeEach(() => {
* [container, cleanup] = withContainer();
* }
* afterEach(() => {
* cleanup();
* }
* it('can render the tooltip', () => {
* wrapper = mount(<Tooltip />, { attachTo: container });
* expect(wrapper).toBeDefined();
* }
* ```
*/
export function withContainer(): [HTMLElement, () => void] {
let container = document.createElement('div');
document.body.appendChild(container);
const cleanup = () => {
document.body.removeChild(container);
document.body.innerHTML = '';
container = null;
};
return [container, cleanup];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment