如何在Jest的功能组件中测试回调函数

时间:2019-11-28 09:24:00

标签: javascript reactjs react-native jestjs enzyme

如果我删除回调()=> ,则测试成功完成,但是我需要此回调来实现功能

组件

const Slider = ({slideSelected, slides}) => {
  const slideClicked = slide => () => { // can't test this
    slideSelected(slide);
  };

  const renderSlide = item => (
    <Slide
      slideClicked={slideClicked}
      item={item}
    />
  );

  return (
    <Carousel
      data={slides}
      renderItem={renderSlide}
    />
  );
};

测试

const slideSelectedFunc = jest.fn();
wrapper.setProps({
  slides: [{ title: 'hello' }],
  slideSelected: slideSelectedFunc,
})
const Item = sliderShallowWrapper.find('Carousel').prop('renderItem');
const itemShallowWrapper = shallow(<Item item={[{ title: 'hello' }]} />);
itemShallowWrapper.props().slideClicked();
expect(slideSelectedFunc).toHaveBeenCalled(); // error

版本笑话24.9

1 个答案:

答案 0 :(得分:0)

slideClicked不是您商品的道具,您需要先找到幻灯片,然后您才能获得正确的道具。

itemShallowWrapper.find("Slide").props().slideClicked();
expect(slideSelectedFunc).toHaveBeenCalled();