Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 无法模拟本机模块_Unit Testing_React Native_Jestjs - Fatal编程技术网

Unit testing 无法模拟本机模块

Unit testing 无法模拟本机模块,unit-testing,react-native,jestjs,Unit Testing,React Native,Jestjs,我正在尝试测试我创建的一个组件,它使用react native maps中的MapView作为子组件。我知道我需要模拟该本机组件,但我编写的内容仍然会显示错误: import 'react-native'; import React from 'react'; import Detail from '../js/components/Detail'; // Note: test renderer must be required after react-native. import rende

我正在尝试测试我创建的一个组件,它使用
react native maps
中的
MapView
作为子组件。我知道我需要模拟该本机组件,但我编写的内容仍然会显示错误:

import 'react-native';
import React from 'react';
import Detail from '../js/components/Detail';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

jest.mock('react-native-maps', () => 'MapView');

it('renders correctly', () => {
  const tree = renderer.create(
    <Detail />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

遇到这个问题时,我将模块添加到了your package.json中jest下的ignore列表中:

"transformIgnorePatterns": [
  "node_modules/(?!react-native|react-native-maps)"
]

在GitHub上找到此问题的解决方案:

我认为问题在于MapView.Marker子组件没有被嘲笑。这个答案也是在模仿子组件

jest.mock('react-native-maps', () => {
  return class MockMapView extends React.Component {
    static Marker = props => React.createElement('Marker', props, props.children);
    static propTypes = { children: React.PropTypes.any };

    render() {
      return React.createElement('MapView', this.props, this.props.children);
    }
  }
});

太好了,谢谢,我试试看。我用的是正确的名字吗?不确定它应该是包名还是组件名是的,非常确定你做得正确。不过,您可能需要向transformignorepatters添加更多内容,我只是一直在运行它,并在其中抛出了有关本机软件包的所有错误。好的,我已经添加了这些内容,并确保为模拟函数使用了正确的名称,但我得到了以下错误
不变冲突:元素类型无效:需要字符串(对于内置组件)或类/函数(用于复合组件),但得到:未定义。检查'AppointmentDetail'的呈现方法。
我想我现在已经找到了,它正在通过GitHub的一个答案,如果您想查看,我会将它添加为一个答案。我认为问题在于我使用的是MapView.Marker子组件,它们没有被模拟。除此之外,还需要以下内容:
jest.mock(`react native maps`,()=>{const react=require('react');})
jest.mock('react-native-maps', () => {
  return class MockMapView extends React.Component {
    static Marker = props => React.createElement('Marker', props, props.children);
    static propTypes = { children: React.PropTypes.any };

    render() {
      return React.createElement('MapView', this.props, this.props.children);
    }
  }
});