Testing component behavior (click) in React-Native with Jest

Suppose I have this component:

import React, { Component } from 'react'; import { Text, TouchableWithoutFeedback, View } from 'react-native'; class MyComp extends Component { onRowPress() { this.myCoolFunction(); } myCoolFunction() { console.log('hi'); } render() { return ( <TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}> <View> <Text>Hello World</Text> </View> </TouchableWithoutFeedback> ); } } export default MyComp; 

How can I simulate 1 click on “TouchableWithoutFeedback” and make sure that “myCoolFunction” is called exactly 1 time?

If this is not necessary, then I would prefer not to add more dependencies except for "reaction-dom" and "reaction-addons-test-utils".

I have seen many manuals claiming this and this, but I'm afraid that they are out of date, and I want to make sure that I don’t go through any unnecessary workarounds and bloat my code.

I have a joke / reaction / reaction to the native in their latest versions.

Edit: The Jest Official Documentation says that DOM tests can be run either with Enzyme or with TestUtils . How can I accomplish this with TestUtils?

+8
reactjs testing react-native jestjs
source share
2 answers

I know that you do not want to add other dependencies, but there is a function in the underscore library called once

Creates a version of a function that can only be called once. Repeated calls to the changed function will have no effect, returning a value from the original call.

This way you will be sure that it has been called once.

0
source share

I know that this answer does not adapt to your requirement not to use any additional dependencies, but I think that you cannot do this only with Jest and Enzyme. Jest provides you with runner, assertion, and snapshot functions, while Enzyme does all the DOM manipulation and event modeling. However, to know that your function was called exactly once, you need something else (i.e., Spy). For this we use sinon , for example:

 ... const onButtonClick = sinon.spy() const wrapper = shallow(<MyComponent onButtonClick={onButtonClick}/>) wrapper.find(`img`).first().simulate(`click`) wrapper.find(`img`).first().simulate(`click`) expect(onButtonClick.calledTwice).toBe(true) ... 
0
source share

All Articles