Testing forms with React and Enzyme

January 5, 2017

Lately at Brave I’ve been adding unit tests for our React code. For our project we use:

We also use ES6 Classes for our react code. So we’ll have a bit of code that looks like this:

class PaymentsTab extends ImmutableComponent {
  render () {
    const minDuration = someFunction()
    return <div>
      <select
        data-test-id='durationSelector'
        className='form-control'
        defaultValue={minDuration}
        onChange={changeSetting.bind(null, this.props.onChangeSetting, settings.MINIMUM_VISIT_TIME)}>>
        <option value='5000'>5 seconds</option>
        <option value='8000'>8 seconds</option>
        <option value='60000'>1 minute</option>
      </select>
    </div>
  }
}

Enzyme makes it really easy to test a component like this but I struggled to test the default value of the form. In the end I found a good thread on their Github repo and ended up testing it this way:

it('defaults to 5 minimum publisher visits', function () {
  const wrapper = shallow(
    <PaymentsTab />
  )

  assert.equal(wrapper.find('[data-test-id="visitSelector"]').node.value, 5)
})

We use data-test-id any time we need a unique identifier for testing purposes. So we can just shallow render the component, call find() on the test id and then use .node.value to get the default value!

Hope that helps!