简体   繁体   中英

Enzyme Button Simulate Not Triggering onPress function

Currently trying to test to see if a button 'onPress' has been called after it is clicked but I'm having some trouble. In my fires onPress function when button is clicked test case in SignUp.test.js it is able to find the button and all but when the click is simulated it says:

Sign Up Page › fires onPress function when button is clicked

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      28 |     // wrapper.find('#navigate').prop('onPress')();
      29 |     wrapper.find('#navigate').at(0).simulate('click');
    > 30 |     expect(onPress).toHaveBeenCalled();
         |                     ^
      31 |   });
      32 | });
      33 |

Here is my code to help:

SignUp.js

const SignUp = ({ navigation }) => {
  const navigateOnPress = () => navigation.navigate('SignIn');

  return (
    <View style={Styles.container}>
      <Text>SignUp</Text>
      <Button
        id="navigate"
        title="Press me"
        onPress={navigateOnPress}
      />
    </View>
  );
};

SignUp.test.js

import React from 'react';
import { shallow } from 'enzyme';

import SignUp from '../../../components/SignUp/SignUp';

describe('Sign Up Page', () => {
  function render(args) {
    const defaultProps = {
      navigation: {
        navigate: jest.fn(),
      },
    };

    const props = {
      ...defaultProps, ...args,
    };

    return shallow(<SignUp {...props} />);
  }
  it('renders the sign up page', () => {
    const wrapper = render();
    expect(wrapper).toMatchSnapshot();
  });

  it('fires onPress function when button is clicked', () => {
    const wrapper = render();
    const onPress = jest.fn();
    wrapper.find('#navigate').prop('onPress')();
    wrapper.find('#navigate').at(0).simulate('click');
    expect(onPress).toHaveBeenCalled();
  });
});

Solved by invoking onPress prop directly and seeing if the function passed into said prop was called.

  it('fires onPress function when button is clicked', () => {
    const navigateToNextPage = jest.fn();
    const props = {
      navigation: {
        navigate: navigateToNextPage,
      },
    };
    const wrapper = shallow(<SignUp {...props} />);
    wrapper.find('#navigate').first().props().onPress();
    expect(navigateToNextPage).toHaveBeenCalledTimes(1);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM