【问题标题】:Jest test fail, alert is not defined开玩笑测试失败,警报未定义
【发布时间】:2020-01-21 09:10:43
【问题描述】:

我在我的 react native 项目中使用 jest,我想测试具有“onPress”的组件。当点击它时,会出现警报。

<ListItem
      testID={'Contact'}
      onPress={() => alert('hello')}
/>

并对其进行测试;

it('test onPress functionality', () => {
    window.alert = jest.fn();
    const wrapper = shallow(
      <Contact
        onPress={window.alert}
      />,
    );
    wrapper
      .findWhere(node => node.prop('testID') === 'Contact')
      .props()
      .onPress();
    expect(window.alert).toHaveBeenCalledWith('hello');
  });

但是这个测试给出了警告错误。

ReferenceError: 未定义警报 onPress={() => alert('hello')}

请帮我解决这个错误。

【问题讨论】:

    标签: reactjs unit-testing react-native jestjs enzyme


    【解决方案1】:

    .use react native Alert

    import {Alert} from 'react-native';
    
    <ListItem
          testID={'Contact'}
          onPress={() => Alert.alert('hello')}
    />
    

    查看文档here

    【讨论】:

      【解决方案2】:

      您的测试不正确,因为您正在测试 'onPress' 作为参数。

      expect(window.alert).toHaveBeenCalledWith('hello');
      

      以上应该可以。

      【讨论】:

      • 感谢修复,但与此无关的错误,现在我修复那里仍然给出同样的错误。
      【解决方案3】:

      这可能不完全相关,但我使用 react.js 从 eslint 收到“未定义”错误。我的解决方案是用“window.alert”明确替换“alert”的所有实例,并且 eslint 完全接受它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 2018-02-13
        • 2018-06-02
        • 2020-08-19
        • 2017-11-19
        • 2019-09-25
        • 2020-10-08
        相关资源
        最近更新 更多