使用Jest和TestUtils测试React表单提交

coo*_*ean 6 coffeescript reactjs jestjs reactjs-testutils

我在submit使用React,TestUtils和Jest 测试表单事件时遇到了麻烦.

我有一个呈现<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>
Run Code Online (Sandbox Code Playgroud)

__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()
Run Code Online (Sandbox Code Playgroud)

相关问题:

Har*_*tor 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')
});
Run Code Online (Sandbox Code Playgroud)