Running the onInput handler

Imagine a simple contentEditable component with an event listener oninput.

export default React.createClass({
  render() {
    return React.createElement('p', {
      contentEditable: true,
      onInput: this.emitChange
    });
  },

  emitChange(e) {
    console.log("Input event occurred", e);
  }
});

In my test, I simulate an event inputon a component (for example, the user enters the letter "a" in the contentEditable tag).

This works in the browser, I can click on the component, press the "a" key, and I will see the "a" in the tag, and it will start console.log. I just can't get it to work in this test:

// Require the code from the block above.
var CE = require('content-editable');

describe('Component', function() {
  it('updates state when we type', function() {
    // Render a component instance and get a handle on it.
    let ce = TestUtils.renderIntoDocument(<CE/>);
    let _ce = ReactDOM.findDOMNode(ce);

    TestUtils.Simulate.input(_ce, {
      key: 'a'
    });

    expect(_ce.textContent).to.equal('a');
  });
});

This test failed because it _ce.textContentis an empty string. I tried to simulate a click on _cebefore simulating input, and this does not fix the problem.

How can I pass the test?

+4
1

, TestUtils.Simulate DOM, React . , , , , , :

export default React.createClass({
  propTypes: {
    onChange: React.PropTypes.func
  },

  render() {
    return React.createElement('p', {
      contentEditable: true,
      onInput: this.emitChange
    });
  },

  emitChange(e) {
    if (this.props.onChange) {
      this.props.onChange(e);
    }
  }
});

, onChange :

describe('Component', function() {
  it('updates state when we type', function() {
    let changeFired = false;
    let ce = TestUtils.renderIntoDocument(<CE onChange={verify} />);
    let _ce = ReactDOM.findDOMNode(ce);

    TestUtils.Simulate.input(_ce, {
      key: 'a'
    });

    function verify(e) {
      changeFired = true;
      expect(e.key).to.equal('a');
    }

    expect(changeFired).to.equal(true);
  });
});

unit test emitChange . , , unit test, , DOM, , , , , - , , - .

unit test DOM textContent innerHTML, . , () .

+2

Source: https://habr.com/ru/post/1617895/


All Articles