2014-11-24 105 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。由於這會引入看起來不必要的額外功能,如果您決定這樣做,可能值得添加註釋,以預計稍後嘗試「修復它」,這將破壞測試。