我可以模拟alert 来测试它的alert 方法是否被调用,但我真正想要测试的是在alert 中按下ok按钮.

import { Alert } from 'react-native';

it('Mocking Alert', () => {
    jest.mock('Alert', () => {
        return {
          alert: jest.fn()
          }
        };
      });

    const spy = jest.spyOn(Alert, 'alert');
    const wrapper = shallow(<Search />);

    wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
    expect(spy).toHaveBeenCalled(); //passes
})

但我完全不确定该如何测试.这是一个通用组件,我正试图测试它.

export default class Search extends Component{

    state = {
      someState: false
    }

    confirmSubmit(){
      this.setState(state => ({someState: !state.someState}))
    }

    onPress = () => {
      Alert.alert(
        'Confirm',
        'Are you sure?'
        [{text: 'Ok', onPress: this.confirmSubmit}] //<-- want to test this
      )
    }

    render(){
      return(
       <View>
         <Button title='Submit' onPress={this.onPress}
       </View>
      )
    }
}

有人试过吗?

推荐答案

我会模拟该模块并将其导入到spy上进行测试.然后触发点击事件.这就叫间谍.从spy中,你可以获得它被调用的参数,使用mock.calls获得onPress方法并调用它.然后可以测试组件的状态.

import Alert from 'Alert'

jest.mock('Alert', () => {
    return {
      alert: jest.fn()
    }
});


it('Mocking Alert', () => {
    const wrapper = shallow(<Search />);
    wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
    expect(Alert.alert).toHaveBeenCalled(); // passes
    Alert.alert.mock.calls[0][2][0].onPress() // trigger the function within the array
    expect(wrapper.state('someState')).toBe(true)
})

React-native相关问答推荐

1.5.1 nxworkspace+react-native 版本的Axios url未定义问题

根据搜索字符串中的每个字母过滤数组

'未能找到 React 根视图的片段' React Native Android RNScreens

在 react native 平面列表中动态定位弹出窗口

React js 做通用头部

按下按钮有一个borderRadius

最近 react-native 版本中的Unable to resolve moduledebuggerWorker 错误

React Native 错误:Animated.event now requires a second argument for options

React-navigation:增加底部标签导航的高度?

背景图像在react中不起作用

Firebase 3.3 实时数据库坚持使用 React Native 0.32 Making a connection attempt

如何将时刻日期转换为字符串并删除时刻对象

React Native onLayout 与 React Hooks

在 navigator pop 上react Native Pass 属性

如何在 React Native 的 MapView 中设置标记

如何在 react-native 中为在后台杀死的 android 应用程序保持状态

在react-native中调试应用程序崩溃

在 React-native 上加载图像时出错:Unexpected character

如何在 React Native 上隐藏 createStackNavigator 的标题?

如何为 TouchableOpacity 组件创建禁用样式?