在本机中测试TextInput组件 [英] Testing TextInput Component in react-native

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

问题描述

使用玩笑测试反应天然中的TextInput变化时,我遇到了一些问题.

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

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

Expected mock function to have been called with: ["test"]

但是没有被调用.

因此,模拟函数永远不会按预期方式调用.我想念什么?

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆