mardi 19 avril 2016

Getting real DOM nodes from enzyme (or: testing non-React events)

Given a React structure like this:

<A>
  <B>
    <div>
      <input>
      { props.focused && <p>focused!</p> }
    </div>
  </B>
</A>

In <A>, in componentWillMount, we've set DOM (non-React) event listeners window for focus and click.

The idea is, when the input is clicked or focused, we call setState in <A>, setting that the input is focused. Conversely, if somewhere on the document that is outside the input gets clicked/focused, we set focused to false.

In <A>'s render, we render <B focused={this.state.focused} />.

We're trying to simulate clicking on the input. Since it's not a React event, we can't use Simulate.

Basically, we want our test to look something like this pseudocode:

wrapper = mount(<A>)
input = wrapper.find(input)
input.click()
assert(wrapper.text().contains('focused!'))

Using Enzyme, how can we access the real, underlying DOM node <input>, so we can send it a click() event?

Things we've tried:

  • Enzyme mount(<A>), access input by className and/or ref: can't find any way to get the actual DOM node
  • Enzyme static rendering (render(<A>)) doesn't work for us because then we're only dealing with a static DOM structure, with no events
  • Using JSDom document => doesn't seem to be a real document, didn't go very far down this path

Aucun commentaire:

Enregistrer un commentaire