Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing TextInput Component in react-native

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"]

But it was not called.

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

like image 694
Hinrich Avatar asked Aug 08 '18 15:08

Hinrich


1 Answers

There is no need to add another library. Jest and Enzyme can perform the required testing. Below is the definition of SearchBar component which receives a function as a prop. The function is called with the text typed.

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

The testing can be carried as follows

    const onSearch = jest.fn();
    const wrapper = shallow(<SearchBar onSearch={onSearch} />);
    wrapper.find('TextInput').simulate('changeText', 'test search text');
    expect(onSearch).toHaveBeenCalledWith('test search text');
like image 65
Prakash Bokati Avatar answered Sep 20 '22 17:09

Prakash Bokati