Skip to content

Instantly share code, notes, and snippets.

@505aaron
Last active July 21, 2020 08:15
Show Gist options
  • Save 505aaron/d5efc2ecc622306cbcc6d3e9c1d7ee9f to your computer and use it in GitHub Desktop.
Save 505aaron/d5efc2ecc622306cbcc6d3e9c1d7ee9f to your computer and use it in GitHub Desktop.
createPortal Mock for react-test-renderer
jest.mock('react-dom');
import React from 'react';
import { createPortal } from 'react-dom';
import renderer from 'react-test-renderer';
import ShallowRenderer from 'react-test-renderer/shallow';
import ReactDOM from 'react-dom';
class Drop extends React.Component {
constructor(props) {
super(props);
this.dropContainer = document.createElement('div');
}
render() {
return (<div>{createPortal(
<div>hello</div>,
this.dropContainer
)}</div>);
}
}
test('Drop renders', () => {
const component = renderer.create(
<Drop />,
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
test('two', () => {
// in your test:
const renderer = new ShallowRenderer();
renderer.render(<Drop />);
const result = renderer.getRenderOutput();
expect(result.type).toBe('div');
expect(result).toMatchSnapshot();
})
import React from 'react';
const reactDom = jest.genMockFromModule('react-dom');
function mockCreatePortal(element, target) {
return (<div>
<div id="content">{element}</div>
<div id="target" data-target-tag-name={target.tagName}></div>
</div>);
}
reactDom.createPortal = mockCreatePortal;
module.exports = reactDom;
@505aaron
Copy link
Author

505aaron commented Dec 1, 2017

It might be smarter to check if the target is a dom type and assert if it isn't. However, this simple example at least helps check that it is an Element.

@tqwewe
Copy link

tqwewe commented Jul 21, 2020

I am receiving an error: parentInstance.children.indexOf is not a function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment