Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub Ant Design's Form getFieldDecorator()?

Tags:

reactjs

antd

I'm trying to do a simple Jest snapshot test of a form but when running the test I get the error:

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

I thought I could just create a stub for getFieldDecorator and pass this in the props but it doesn't work.

This is the test:

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

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

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

expect(wrapper).toMatchSnapshot();

});

This is the render() method in my component:

  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>

I'm exporting my component as:

export default withRouter(Form.create()(LoginForm));
like image 879
J_P Avatar asked Dec 07 '18 13:12

J_P


1 Answers

You're on correct way, the only thing you've missed is that the getFieldDecorator should return a function, so you need to mock it accordingly i.e.:

const testForm = {
  getFieldDecorator: jest.fn( opts => c => c )
};
like image 89
Alex Avatar answered Oct 14 '22 04:10

Alex