Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate press of React Native Switch component using Jest and Enzyme [duplicate]

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.

like image 591
Attila Avatar asked Oct 19 '18 03:10

Attila


Video Answer


1 Answers

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!

like image 184
Attila Avatar answered Oct 03 '22 00:10

Attila