Jest+enzyme 測試antd form

最近寫單元測試,antd 的form 表單遇到了一些坑點線總結(jié)如下:

const wrapper = mount(<EventRegistrationForm/>);
  1. input 框填入字符串值
<Form.Item label="name">
            {getFieldDecorator('name', {
              rules: [{
                required: true
              }],
            })(<Input />)}
 </Form.Item>

則在input 中填入值如:

  wrapper.find('input#name').simulate('change', { target: { value: 'test' } });
  1. input 框中填整數(shù)值
 <Form.Item label="phoneNumber">
            {getFieldDecorator('phoneNumber', 
              rules: [{
                message: t('eventForm.errorMessage.phoneNumberInvalid'),
                pattern: new RegExp('^[0-9]{10}$')
              }],
            })(
              <Input/>
            )}
 </Form.Item>

在input 中填入值如下:

wrapper.find('input#phoneNumber').prop('onChange')
({ currentTarget: { value: 1882925032 } });
  1. 對于select 的選擇
<Form.Item label="budget">
            {getFieldDecorator('budget', {
              rules: [{
                required: true,
              }],
            })(
              <Select placeholder="">
                <Select.Option value="A">A</Select.Option>
                <Select.Option value="B">B</Select.Option>
                <Select.Option value="C">C</Select.Option>
              </Select>
            )}
 </Form.Item>

測試代碼如下去模擬點擊事件:

wrapper.find('#budget .ant-select-selection__rendered').simulate('click');
wrapper.find('.ant-select-dropdown-menu li').at(2).simulate('click');
  1. checkBox的多選
 <Form.Item label="purchaseObjective">
            {getFieldDecorator('purchaseObjective', {
              rules: [{
                required: true,
              }],
            })(
              <Checkbox.Group>
                <Checkbox value="A">A</Checkbox>
                <Checkbox value="B">B</Checkbox>
                <Checkbox value="C">C</Checkbox>
              </Checkbox.Group>
            )}
  </Form.Item>

測試代碼如下:

 wrapper.find('#purchaseObjective input[value="A"]').simulate('change', { target: { value: 'A' } });
  1. 表單的提交
 <Form.Item>
     <Button type="primary" htmlType="submit" className="btn-submit">
         {isShowLoading && <Icon type="loading" theme="outlined" />}
         {t('eventForm.button.submit')}
     </Button>
 </Form.Item>

測試代碼:

wrapper.find('form').simulate('submit');

不能通過找到button 元素然后click 的方法去提交表單

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容