在 react-native 中测试 TextInput 组件

Hin*_*ich 6 javascript jestjs react-native enzyme

我在测试react-nativejest酶的TextInput变化时遇到了一些问题。

我处理用户输入的组件基本上是这样的(简化):

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

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

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);
});
Run Code Online (Sandbox Code Playgroud)

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

预期的模拟函数已被调用:["test"]

但它没有被调用。

因此,永远不会按预期调用模拟函数。我错过了什么?

Dav*_*llo 5

我能够使用react-native-testing-library.

// ...
import { render, act, fireEvent } from 'react-native-testing-library'
// ...
it ('does stuff', () => {
  const mock = jest.fn()
  const component = render(<Search onSearchTextChange={mock}/>)
  fireEvent.changeText(component.findByType(TextInput), 'test')
  expect(mock).toHaveBeenCalledWith('test')
})

Run Code Online (Sandbox Code Playgroud)


Pra*_*ati 5

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

const SearchBar = ({onSearch}) => {
  return (
    <View>
      <TextInput
        onChangeText={text => onSearch(text)}
      />
    </View>
  );
};
Run Code Online (Sandbox Code Playgroud)

测试可以如下进行

    const onSearch = jest.fn();
    const wrapper = shallow(<SearchBar onSearch={onSearch} />);
    wrapper.find('TextInput').simulate('changeText', 'test search text');
    expect(onSearch).toHaveBeenCalledWith('test search text');
Run Code Online (Sandbox Code Playgroud)