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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With