Last active
July 21, 2020 08:15
-
-
Save 505aaron/d5efc2ecc622306cbcc6d3e9c1d7ee9f to your computer and use it in GitHub Desktop.
createPortal Mock for react-test-renderer
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
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(); | |
}) |
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 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; |
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
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.