无法在Redux-Form单元测试中模拟表单点击

时间:2018-01-13 00:38:13

标签: reactjs redux react-redux redux-form

我正在尝试使用redux-form模拟表单提交以进行单元测试,我甚至无法调用onSubmit处理程序。

测试代码段

import React from 'react';
import { AddBudgetForm } from '../../../src/Budget/components/AddBudgetForm';
import { SubmissionError } from 'redux-form';
import { shallow, configure } from 'enzyme';
import sinon from 'sinon';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

describe("AddBudgetForm Component", () => {
  let budgetForm = null;
  let submitting, touched, error, reset,addBudget, addBudgetResponse, handleSubmit
  beforeEach(() => {
    submitting = false
    touched = false
    error = null
    reset = sinon.spy()
    addBudgetResponse = Promise.resolve()
    handleSubmit = fn => fn
  })
  const buildForm = () => {
    addBudget = sinon.stub().returns(addBudgetResponse)
    const props = {
      addBudget,
      submitting: submitting,
      fields: {
        budgetName: {
          value: '',
          touched: touched,
          error: error
        }
      },
      handleSubmit,
      reset
    }
    return shallow(<AddBudgetForm {...props}/>)
  }

  it ('Calls reset after onSave', () => {
    budgetForm = buildForm();
    budgetForm.find('[type="submit"]').simulate('submit')
  })

})

上面,我正在嘲笑一些行为,我的测试将不可避免地从sinon spy检查callCount。

表格

  submit(dataValues) {
    console.log("called")
    dataValues.preventDefault();
    this.props.addBudget({})

  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <div className='form-group has-danger'>
         <form onSubmit={(e) => this.submit(e)}>
          <Field name='budgetName' component={this.categoryInput} placeholder="Enter Category of Budget" label="Budget Category"/>
          <button type='submit' className='btn btn-primary'>Submit</button>
        </form>
      </div>
    )
  }
}

我稍微缩短了我的代码,但想法是onSubmit应该调用该函数,但我甚至无法获得控制台日志来打印。不确定为什么会发生这种情况。

1 个答案:

答案 0 :(得分:0)

如果要模拟提交事件,则应选择表单标记。使用上面的代码应该是一个单击。所以:

budgetForm.find('[type="submit"]').simulate('click')