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 do I go about simulating 1 click on the 'TouchableWithoutFeedback' and making sure that 'myCoolFunction' was called exactly 1 times?
If it's not a must, then I would prefer to not add more dependencies other than 'react-dom' and 'react-addons-test-utils'.
I saw a lot of guides claiming this and that but I fear they are outdated and I want to be sure that I'm not going through some unneeded workarounds and bloating my code.
I have jest/react/react native in their latest versions.
Edit: In Jest's official documentation it says that DOM tests can be done with either Enzyme or the TestUtils. How can I accomplish this using the TestUtils?
Setup Run yarn test to run tests with Jest. If you are upgrading your react-native application and previously used the jest-react-native preset, remove the dependency from your package. json file and change the preset to react-native instead.
Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.
I know this answer doesn’t adjust to your requirement of not using any additional dependencies, but I think you can’t do that just with Jest and Enzyme. Jest provides you with the runner, assertion functions and snapshot testing and Enzyme does all the DOM manipulations and event simulation. However, to know that your function was invoked exactly one time you’ll need something else (i.e. a spy). We use sinon
for that, like so:
...
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)
...
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