Reputation: 739
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?
Upvotes: 9
Views: 2007
Reputation: 1453
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)
...
Upvotes: 1
Reputation: 399
I know you don't wanna add other dependencies, but there is a function in the underscore library called once
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call.
This way you will be sure it was called once.
Upvotes: -1