Dave Stein
Dave Stein

Reputation: 9316

How do I properly test input change events with Enzyme?

I am giving Jest/Enzyme a try, and am having trouble with a simple example I am trying to create.

I have a small component with an input that should update the text of a DIV. I want to write a test proving the DIV got updated.

My test is simply this:

const app = shallow(<App {...state} />);
const input = app.find('input');

input.simulate('keyDown', {keyCode: 72});
input.simulate('keyDown', {keyCode: 73});
input.simulate('change', {target: input});

expect(app.find('[test="mirror"]').text()).toEqual('hi');

I know that the input is actually returning a ShallowWrapper. You can see in my component below, I am updating state by looking at e.target.value. Is there a way to pass the actual DOM node to my simulation of change? Will simulating the keyDown actually update the input value? Or should I do that a different way?

import React from 'react'
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mirror: ''
    };
    this.updateMirror = this.updateMirror.bind(this);
  }

  updateMirror(e) {
    let val = e.target.value;
    this.setState((prevState, props) => {
      return {
        mirror: val
      };
    });
  }

  render() {
    return <div>
      <div><input type="text" onChange={this.updateMirror} /></div>
      <div test="mirror">{this.state.mirror}</div>
    </div>
  }
}
export default App

Upvotes: 8

Views: 11271

Answers (1)

toufek khoury
toufek khoury

Reputation: 3374

Try something like this :

const wrapper = shallow(<App {...state} />);
wrapper.find('input').simulate('change', {target: {value: 'Your new Value'}});
expect(wrapper.state('mirror')).toBe('Your new Value');

Upvotes: 13

Related Questions