6

我在submit使用 React、TestUtils 和 Jest 测试表单事件时遇到问题。

我有一个渲染<form>DOM 元素的组件;同一个组件还有一个处理onSubmit事件和记录语句的方法。我的目标是模拟onSubmit处理程序并断言它被调用。

表单组件.cjsx

module.exports = React.createClass

  # Handle form submissions
  handleSubmit: (e) ->
    console.log 'Make async call'

  # Render a form
  render: ->
    <form onSubmit={@handleSubmit}>
      <input type="submit" />
    </form>

__tests__/test-form-component.coffee

jest
  .dontMock '../form-component'

React = require 'react/addons'
TestUtils = React.addons.TestUtils
FormComponent = require '../form-component'

describe 'FormComponent', ->
  it 'creates a log statement upon form submission', ->
    # Render a FormComponent into the dom
    formInstance = TestUtils.renderIntoDocument(<FormComponent />)

    # Mock the `handleSubmit` method
    formInstance.handleSubmit = jest.genMockFunction()

    # Simulate a `submit` event on the form
    TestUtils.Simulate.submit(formInstance)
    # TestUtils.Simulate.submit(formInstance.getDOMNode()) ???

    # I would have expected the mocked function to have been called
    # What gives?!
    expect(formInstance.handleSubmit).toBeCalled()

相关问题:

4

2 回答 2

0

There's an issue with the way React calls event handlers that causes the original handler function to continue to be called even if you attempt to mock it first.

This can apparently be avoided by switching to the ES6 class syntax to create component classes, but another simple workaround is to have the event handler just call a second function and mock that. For example:

onSubmit: function() {
    this.handleSubmit();  // extra fn needed for Jest
},
handleSubmit: function(){
    this.setState({
        submitted: true
    });
}

You would set the form's onSubmit={this.onSubmit} and mock handleSubmit instead of onSubmit. Since this introduces a seemingly unnecessary extra function, if you decide to do this it's probably worth adding a comment to anticipate later attempts to "fix it" which would break the test.

于 2015-03-14T12:16:44.040 回答
0

你的问题到底是什么?

React.addons.TestUtils.Simulate.submit()为我工作。

如果它可以帮助,我处于类似的情况,我以这种方式测试提交处理程序(使用sinon.jsmochachai):

var renderDocumentJQuery = $(renderDocument.getDOMNode())
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
    requests.push(xhr);
};
renderDocumentJQuery.find('input#person_email').val('test@email.com');
React.addons.TestUtils.Simulate.submit(renderDocumentJQuery.find('form')[0]);
var requestFired = requests[0];
this.xhr.restore();
it('should fire an AJAX with the right params', function(){
  assert.equal(requestFired.requestBody,'campaign_id=123&owner_id=456&person%5Bemail%5D=test%40email.com')
});
it('should fire an AJAX with a POST method', function(){
  assert.equal(requestFired.method,'POST')
});
it('should fire an AJAX with the correct url', function(){
  assert.equal(requestFired.url,'url-for-testing')
});
于 2015-03-06T22:39:10.360 回答