【问题标题】:Testing lodash debounce in react-native functional component using Jest / Enzyme使用 Jest / Enzyme 在 react-native 功能组件中测试 lodash debounce
【发布时间】:2019-07-26 07:07:12
【问题描述】:

我正在尝试测试是否最终调用了 props.onPress,但我收到“TypeError:debouncePress 不是函数”。任何想法为什么?

import _ from 'lodash';

export const Button = props => {
  const { debounceTime } = props;
  const debouncePress = _.debounce(() => {
    if (props.onPress) props.onPress();
  }, debounceTime, { leading: true, trailing: false });

  const handlePress = () => {
    debouncePress();
  };

  return (
    <TouchableOpacity testID="touchableOpacity" onPress={handlePress}>
      {props.label ?<Text>{props.label}</Text> : props.children}
    </TouchableOpacity>
  );
};

这是目前的测试

it('should call onPress when press event occurs', () => {
    wrapper = shallow(<Button onPress={jest.fn()} />);
    wrapper.find({ testID: 'touchableOpacity' }).simulate('press');
    expect(props.onPress).toHaveBeenCalled();
});

【问题讨论】:

  • 我看到的一个问题是Button 是用arrow function expression 定义的,所以this 最终会成为外部范围的this,它可能有也可能没有props定义。我认为您打算这样做:const { debounceTime } = props;。至于您看到的错误,您是否嘲笑lodash?这是我能想到的唯一会导致 debouncePress 不是函数的事情。

标签: javascript react-native jestjs lodash enzyme


【解决方案1】:

我看不到你在测试中通过debouncePress 的地方!!

wrapper = shallow(<Button onPress={jest.fn()} />); // you passing onPress but debouncePress is undefined

const { debounceTime } = props; 期望 debounceTime 作为属性传递,但它不在您的测试中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 2020-04-08
    • 2020-07-17
    • 1970-01-01
    • 2017-02-12
    • 2018-08-20
    相关资源
    最近更新 更多