【问题标题】:How do I stub Ant Design's Form getFieldDecorator()?如何存根 Ant Design 的表单 getFieldDecorator()?
【发布时间】:2018-12-07 13:21:00
【问题描述】:

我正在尝试对表单进行简单的 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));

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    你的方法是正确的,你唯一错过的是 getFieldDecorator 应该返回一个函数,所以你需要相应地模拟它,即:

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

    【讨论】:

    • 非常感谢 Alex :)
    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 2020-02-22
    • 2021-05-20
    • 2019-08-02
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多