2014-11-24 106 views
5

我遇到问题,使用React,TestUtils和Jest测试表单submit事件。测试反应表单提交使用Jest&TestUtils

我有一个组件呈现<form> DOM元素;同一个组件也有一个方法来处理事件并记录一条语句。我的目标是嘲笑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> 

__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() 

相关问题:

回答

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('[email protected]'); 
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') 
}); 
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。由于这会引入看起来不必要的额外功能,如果您决定这样做,可能值得添加注释,以预计稍后尝试“修复它”,这将破坏测试。