在react-native中测试TextInput组件

2023-11-24

我在测试时遇到一些问题TextInput改变在反应本机 with jest and enzyme.

我处理用户输入的组件基本上如下所示(简化):

class Search extends React.PureComponent {
  onSearchTextChange = input => {
    // do something awesome
  };
  render() {
    return (
      <View>
        <TextInput
          onChangeText={debounce(this.onSearchTextChange, 800)}
        />
      </View>
    );
  }
}

我想测试文本输入行为。这就是测试现在的样子:

it('should render a text input and react to user input', done => {
  const mockOnSearchTextChange = jest.fn();
  Search.prototype.onSearchTextChange = mockOnSearchTextChange;

  const tree = shallow(<Search />);
  const textInput = tree.find('TextInput');
  expect(textInput).toHaveLength(1);
  textInput.simulate('changeText', { target: { value: 'test' } });
  expect(mockOnSearchTextChange).not.toHaveBeenCalled();
  setTimeout(() => {
    expect(mockOnSearchTextChange).toHaveBeenCalledWith('test');
    done();
  }, 1500);
});

运行此测试时,我收到此错误消息

预期的模拟函数已被调用: [“测试”]

但它没有被调用。

因此,模拟函数永远不会按预期被调用。我缺少什么?


无需添加另一个库。 Jest 和 Enzyme 可以执行所需的测试。下面是 SearchBar 组件的定义,它接收一个函数作为 prop。使用键入的文本调用该函数。

const SearchBar = ({onSearch}) => {
  return (
    <View>
      <TextInput
        onChangeText={text => onSearch(text)}
      />
    </View>
  );
};

测试可以按如下方式进行

    const onSearch = jest.fn();
    const wrapper = shallow(<SearchBar onSearch={onSearch} />);
    wrapper.find('TextInput').simulate('changeText', 'test search text');
    expect(onSearch).toHaveBeenCalledWith('test search text');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在react-native中测试TextInput组件 的相关文章

随机推荐