简体   繁体   English

酶按钮模拟不触发 onPress 功能

[英]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.目前正在尝试测试是否在单击“onPress”按钮后调用了它,但我遇到了一些麻烦。 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:在我在SignUp.test.js fires onPress function when button is clicked测试用例中,它能够找到该按钮,但在模拟单击时它说:

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注册.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注册.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.通过直接调用 onPress 道具并查看传入该道具的函数是否被调用来解决。

  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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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