gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:32:25 25 4
gpt4 key购买 nike

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

我有一个渲染 <form> 的组件DOM 元素;同一组件还有一个处理 onSubmit 的方法事件并记录一条语句。我的目标是 mock 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()

相关问题:

最佳答案

您的问题到底是什么?

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')
});

关于coffeescript - 使用 Jest 和 TestUtils 测试 React 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27115332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com