如何使用Jest和Enzyme测试按钮的onClick道具

时间:2018-11-29 08:43:24

标签: reactjs jestjs

我正在尝试测试一个在React中具有onClick功能的按钮。我的按钮如下所示:

<button 
          id='emailButton'
          className={classes.sceContactHeaderButton}
          data-toggle='collapse'
          data-target='#editEmailContact'
          onClick={props.handleToggle}
          tabIndex={0}
          title={(props.email.isOpen) ? 'Close Section' : 'Open Section'}
        >
          <span>{(props.email.isOpen) ? 'Close' : 'Details'}</span>
          <i className={(props.email.isOpen) ? 'fa fa-angle-up' : 'fa fa-angle-down'} />
        </button>

我对onClick()方法的测试是:

  it('check if the onClick method of the button exists', () => {
        wrapper.find('#emailButton').children().at(0).prop('onClick')();
    });

但是我收到一个错误消息:

TypeError: wrapper.find(...).children(...).at(...).prop(...) is not a function

我在做什么错?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我认为您想要的是模拟事件,而不是将其称为道具。这是有关如何执行此操作的示例:

 it('should call mock function when button is clicked', () => {
   const tree = shallow(
     <Button name='button test' handleClick={mockFn} />
   );
   tree.simulate('click');
   expect(mockFn).toHaveBeenCalled();
 });

我在本文https://medium.com/backticks-tildes/testing-your-react-component-with-jest-and-enzyme-276eef45bea0

中找到了此示例

答案 1 :(得分:0)

在进行过多次尝试后成功点击props.button

MainButton.js

export default function MainButton(props) {
    let ButtonComponent = TouchableOpacity;

    if (Platform.Version >= 21) {
        ButtonComponent = TouchableNativeFeedback;
    }

    return (
        <View style={{...styles.buttonContainer, ...props.style}}>
            <ButtonComponent activeOpacity={0.6} onPress={props.onPress}> //Want to test props.onPress
                <View style={styles.button}>
                    <Text style={styles.buttonText}>{props.children}</Text>
                </View>
            </ButtonComponent>
        </View>
    );
}

MainButton.test.js

import { TouchableOpacity } from 'react-native';

describe('Main Button Component', () => {
    const goToMainScreen = jest.fn();
    const component = shallow(
        <MainButton onPress={goToMainScreen}>
            NEXT
        </MainButton>
    );

    it('should call onPress on click', async() => {
        const wrapper = component.find(TouchableOpacity);
        wrapper.getElement().props.onPress()
        expect(goToMainScreen).toHaveBeenCalled();
    });
});