I'm trying to test a React Native component, which is basically a wrapper for Switch.
It looks like this (styles and extra code removed):
render() {
return (
<View>
<View>
<View>
<Switch
onValueChange={() => this.onChange(!this.state.value)}
value={this.state.value}
/>
</View>
</View>
</View>
);
}
This component doesn't have on onChange
method itself, but the class it extends does. I want to make sure that when I click on this Switch, the onChange
is called with the proper value (i.e. with either true
or false
).
My test looks like this (I added a mocked onChange
method to it, to make it easier to test the action of the press):
it('calls onChange with proper values when pressed', () => {
const onChangeHandler = jest.fn();
const wrapper = shallow(
<Toggle />
);
wrapper.instance().onChange = onChangeHandler;
wrapper.simulate('press');
expect(wrapper.instance().onChange).toBeCalledWith(true);
});
However, this test fails, and onChange
is not called. I'm not sure where the fault in my test is.
I've discovered that I don't need to simulate the press, but that I can simulate the onValueChange
instead (i.e. the thing that is triggered when the toggle is pressed).
First I find my Switch
component in my test, using a testID
prop I gave it:
const Switch = wrapper.find('[testID="switch"]');
And then I use this to get around simulating a press and simulate the onChange instead:
Switch.simulate('valueChange');
This essentially has the same result as testing a press, and works for me!
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