我正在尝试对表单进行简单的Jest快照测试,但是在运行测试时出现错误:

Uncaught [TypeError: getFieldDecorator(...) is not a function]


我以为我可以为getFieldDecorator创建一个存根,并在道具中传递它,但它不起作用。

这是测试:

  it('renders correctly initially', () => {

const testForm = {
  getFieldDecorator: jest.fn()
};

const wrapper = mount(
  <Router>
    <LoginForm form={testForm} />
  </Router>
);

expect(wrapper).toMatchSnapshot();


});

这是我组件中的render()方法:

  render() {
const { form } = this.props;
const { getFieldDecorator } = form;

return (
  <Form onSubmit={this.handleSubmit} className="login-form">
    <FormItem>
      {getFieldDecorator('username', {
        rules: [{ required: true, message: 'Please enter your username!' }]
      })(
        <Input
          prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
          placeholder="Username"
        />
      )}
    </FormItem>


我将组件导出为:

export default withRouter(Form.create()(LoginForm));

最佳答案

您采用的是正确的方法,唯一想念的是getFieldDecorator应该返回一个函数,因此您需要相应地模拟它,即:

const testForm = {
  getFieldDecorator: jest.fn( opts => c => c )
};

07-28 10:51