使用Jest& amp;测试反应表格提交TestUtils

时间:2014-11-24 22:25:25

标签: coffeescript reactjs jestjs reactjs-testutils

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

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

形状component.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>

__测试__ / 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()

相关问题:

2 个答案:

答案 0 :(得分: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')
});

答案 1 :(得分:0)

有一个issue with the way React calls event handlers导致原始处理函数继续被调用,即使你先尝试模拟它。

显然可以通过切换到ES6 class syntax来创建组件类来避免这种情况,但另一个简单的解决方法是让事件处理程序只调用第二个函数并模拟它。例如:

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

您可以设置表单onSubmit={this.onSubmit}并模拟handleSubmit而不是onSubmit。由于这会引入一个看似不必要的额外功能,如果您决定这样做,可能值得添加注释以预测以后尝试修复它&#34;哪会破坏考验。