如何通过玩笑或酵素读取孩子的功能特性

时间:2020-08-12 09:29:40

标签: reactjs jestjs

这是我的React组件代码的一部分:

<div style={{ width }}>
  <FormField
    label='Select a type'
    labelPlacement='top'
    className='cdsdrop'
  >
    {({ getButtonProps }) => (
      <Dropdown
        {...getButtonProps({
          id: 'typeDropDown',
          source: data,
          onChange: this.handleInputChange,
          options: data
        })}
      />)}
  </FormField>
</div>

是开玩笑的框架的新手。我开始为提交按钮编写测试用例,并在下拉列表值为空后禁用了重置,选择下拉按钮后应该启用该选项。

当我使用props().label时会得到标签,但是当我打电话给孩子时会出错。

这是 mytest 组件

describe('Buttons should be disabled on page load', () => {
    
    it('submit and reset buttons are disabled when type is empty', () => {  
        const wrapper = shallow(<CdsNettingActions/>);
        const submitButton = wrapper.find('WithStyles(Component).cdssubmit');
        const resetButton = wrapper.find('WithStyles(Component).cdsreset');
        const dropDown = wrapper.find('WithStyles(Component).cdsdrop');
        const drop1=dropDown.props().children();
        
        console.log('drop',drop1);
        
        expect(submitButton.prop('disabled')).toEqual(true);
        expect(resetButton.prop('disabled')).toEqual(true);
    });
});

但是出现以下错误:

TypeError:无法读取未定义的属性“ getButtonProps” className ='cdsdrop'>

当我完成控制台日志记录后,children函数如下所示:

         getButtonProps({
            id: 'typeDropDown',
            borderless: true,
            buttonWidth: width,
            source: data,
            onChange: _this4.handleInputChange,
            options: data
         }))

请帮助我阅读下拉菜单中的选项。

我使用空心的 strong文字反应16

1 个答案:

答案 0 :(得分:0)

因此,您的FormField的{​​{1}}属性是一个回调,它期望具有children属性的对象:

getButtonProps

这就是为什么当你刚做

{({ getButtonProps }) => (

它崩溃-没有带有const drop1=dropDown.props().children(); 的对象。您可以传递此参数,但是接下来您会发现getButtonProps变量包含React对象,而不是酶的ShallowWrapper。因此,诸如drop1之类的任何检查都将失败“ prop不是函数”。

因此您可以使用renderProp()

expect(drop1.prop('something')).toEqual(2)

或者改为使用const drop1 = dropDown.renderProp('children')({ getButtonProps: () => ({ id: 'typeDropDown', borderless: true, buttonWidth: someWidth, source: mockedSource, onChange: mockedOnChange, options: mockedOptions }) }); 更容易。