how to check the actual DOM node using react enzyme
You can use wrapper.getDOMNode()
Enzyme docs
Perhaps you are looking for enzyme's instance()?
const wrapper = mount(<input type="text" defaultValue="hello"/>)
console.log(wrapper.instance().value); // 'hello'
PS:
instance()
should give you a ReactComponent
, from which you can use ReactDOM.findDOMNode(ReactComponent) to get a DOMNode. However, when I did that, like the following, it was the exact same object as wrapper.instance()
:
import ReactDOM from 'react-dom'
const wrapper = mount(<input type="text" defaultValue="sup"/>)
console.log(ReactDOM.findDOMNode(wrapper.instance()) == wrapper.instance()) // true
I don't understand why that is. If you console.log()
either one of those, you'll see a HTMLInputElement
, but it will contain lots of non-native DOM node looking stuff:
HTMLInputElement {
'__reactInternalInstance$yt1y6akr6yldi':
ReactDOMComponent {
_currentElement:
{ '$$typeof': Symbol(react.element),
type: 'input',
key: null,
ref: null,
props: [Object],
_owner: [Object],
_store: {} },
I ran into this same problem. In my case, I was testing something built with react-aria-modal
, which renders the overlay div in a different part of the DOM than the initial element rendered with mount()
. In order to test that this renders properly, I needed to look more globally at the DOM. For this, I used the attachTo
option of render()
to ensure that my test DOM looks like it should in a real browser. Here is a good general description of the technique from the docs.
Depending on what you need, you can use Tyler Collier's approach for more local parts of the DOM (findDOMNode
using instance()
) or mine for a more global view.
Here's a sample spec for my use case, showing how to setup/use/teardown the mock DOM:
import MyModalComponent from '../components/my-modal-component'
import React from 'react'
import { jsdom } from 'jsdom'
import { mount } from 'enzyme'
describe('<MyModalComponent /> Component', function(){
let wrapper
beforeEach(function(){
window.document = jsdom('')
document.body.appendChild(document.createElement('div'))
})
afterEach(function(){
wrapper.detach()
window.document = jsdom('')
})
it('renders the modal closed by default', () => {
wrapper = mount(
<MyModalComponent prop1={"foo"}
prop2={"bar"}
/>, { attachTo: document.body.firstChild }
)
expect(wrapper.html()).to.contain('Content in component')
expect(document.body.innerHTML).to.not.contain('Content in overlay')
})
})