首页 > 解决方案 > 如何在玩笑或酶中读取儿童功能属性

问题描述

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

<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>

我是 jest 框架的新手。我开始为提交按钮编写测试用例,当下拉值为空时,重置被禁用,选择下拉按钮后应该启用。

当我使用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”=“cdsdrop”>

当我进行控制台记录时,子函数如下所示:

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

请帮助我如何从下拉列表中读取选项。

我正在使用浅的强文本反应 16

标签: reactjsjestjs

解决方案


所以你FormFieldchildrenprop 是一个回调,它需要一个具有getButtonProps属性的对象:

{({ getButtonProps }) => (

这就是为什么当你做

const drop1=dropDown.props().children();

它崩溃了 - 没有对象getButtonProps。你可以传递这个参数,但接下来你会发现drop1变量包含 React 对象,而不是 Enzyme 的 ShallowWrapper。因此,任何检查expect(drop1.prop('something')).toEqual(2)都将失败“道具不是函数”。

所以你要么使用renderProp()

const drop1 = dropDown.renderProp('children')({
  getButtonProps: () => ({
    id: 'typeDropDown',
    borderless: true,
    buttonWidth: someWidth,
    source: mockedSource,
    onChange: mockedOnChange,
    options: mockedOptions
  })
});

或者也许它更容易使用mount()


推荐阅读