如何存根 Ant Design 的表单 getFieldDecorator()?



我试图对表单进行一个简单的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 )
};

最新更新