为了使用jest进行单元测试,我用以下代码模拟了expo目录:
jest.mock('expo', () => {
const { View } = require('react-native');
const constantsMock = { // the camera class has constants defined on it
Type: {
back: 'BACK',
front: 'FRONT',
},
};
const cameraMock = Object.assign({}, View, { Constants: constantsMock }); // assign so we can modify a copy, not the orig View - since its passed by reference
return {
Permissions: {
askAsync: jest.fn(),
},
Camera: cameraMock,
CameraObject: View,
};
});这是可行的-但会导致react记录以下错误:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `InKeyboardCamera`.
in InKeyboardCamera通过消除过程(即,取出渲染组件的一部分,并检查它何时被抛出以及何时未被抛出),我追踪到产生此错误的组件如下所示:
(<SimpleLineIcons name="refresh" size={19} color="white" />)与以下语句一起导入的:
import { SimpleLineIcons } from '@expo/vector-icons';这很奇怪,因为我没有模拟@expo/vector-icons模块,它可以实时工作,但不能在测试环境中工作。但果不其然,注销该文件中的console.log(SimpleLineIcons)会导致undefined。
我用下面的代码消除了这个错误:
jest.mock('@expo/vector-icons', () => {
const { View } = require('react-native');
return {
SimpleLineIcons: View,
Ionicons: View,
};
});但它留下了一个问题:为什么模拟expo包会影响@expo/vector-icons包?
发布于 2019-08-11 01:02:47
Expo基本上有一个从SDK32内置的'expo-vector-icons‘模块。这就是为什么在通过Expo创建项目时不需要单独安装'expo-vector-icons‘模块,单独安装它们可能会导致冲突。
通过查看在preset文件中被忽略的转换模式,可以理解这一点。
expo/packages/jest-expo/jest-preset.js
jestPreset.transformIgnorePatterns = [
'node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|sentry-expo|native-base|react-native-svg)',
];https://stackoverflow.com/questions/57443897
复制相似问题