mardi 22 décembre 2015

Should I avoid refs in favor of e.target, for testing purposes?

I've frequently been writing components like this:

<input
    ref="ckbx"
    type="checkbox"
    checked={this.props.checked}
    onChange={() => this.props.onChange(this.refs.ckbx.checked)}
/>

However, I've now discovered that this is difficult to unit-test. In particular, when using either Simulate.change or Simulate.click, the callback is passed the initial value of the checkbox instead of the new value (as happens in the browser). This behavior persists when I add { target: { checked: false } } as the second argument to each Simulate call.

It works if I instead use

<input
    type="checkbox"
    checked={this.props.checked}
    onChange={e => this.props.onChange(e.target.checked)}
/>

So, my questions are

  • Is this the preferred way to write input logic?
  • Is this the only unit-testable way to write input logic? It really doesn't seem that flexible (what if I need to consider multiple refs?).
  • Can I get my existing method to work?
  • Should I change all my components? (Not difficult, but I don't want to do it if there's a better way.)

Aucun commentaire:

Enregistrer un commentaire