本文介绍了在 react-native 中测试 TextInput 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 jestenzyme 测试 react-native 中的 TextInput 更改时遇到一些问题.>

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

class Search 扩展 React.PureComponent {onSearchTextChange = 输入 =>{//做一些很棒的事情};使成为() {返回 (<文本输入onChangeText={debounce(this.onSearchTextChange, 800)}/></查看>);}}

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

it('应该呈现文本输入并对用户输入做出反应', done => {const mockOnSearchTextChange = jest.fn();Search.prototype.onSearchTextChange = mockOnSearchTextChange;const tree = 浅();const textInput = tree.find('TextInput');期望(文本输入).toHaveLength(1);textInput.simulate('changeText', { target: { value: 'test' } });期望(mockOnSearchTextChange).not.toHaveBeenCalled();setTimeout(() => {期望(mockOnSearchTextChange).toHaveBeenCalledWith('test');完毕();}, 1500);});

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

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

但它没有被调用.

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

解决方案

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

//...从'react-native-testing-library'导入{渲染,行为,火事件}//...它('做东西',()=> {const mock = jest.fn()const component = render(<Search onSearchTextChange={mock}/>)fireEvent.changeText(component.findByType(TextInput), 'test')期望(模拟).toHaveBeenCalledWith('测试')})

I have some problems with testing TextInput changes in react-native with jest and enzyme.

My component that handles user input basically looks like this (simplified):

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

I want to test the text input behaviour. This is what the test looks like right now:

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);
});

When running this test, I get this error message

So the mocked function is never called as expected. What am I missing?

解决方案

I was able to do this using 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')
})

这篇关于在 react-native 中测试 TextInput 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:22