首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么用jest.mock模拟expo时,@expo/向量图标没有定义?

为什么用jest.mock模拟expo时,@expo/向量图标没有定义?
EN

Stack Overflow用户
提问于 2019-08-11 00:35:34
回答 1查看 910关注 0票数 0

为了使用jest进行单元测试,我用以下代码模拟了expo目录:

代码语言:javascript
复制
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记录以下错误:

代码语言:javascript
复制
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

通过消除过程(即,取出渲染组件的一部分,并检查它何时被抛出以及何时未被抛出),我追踪到产生此错误的组件如下所示:

代码语言:javascript
复制
(<SimpleLineIcons name="refresh" size={19} color="white" />)

与以下语句一起导入的:

代码语言:javascript
复制
import { SimpleLineIcons } from '@expo/vector-icons';

这很奇怪,因为我没有模拟@expo/vector-icons模块,它可以实时工作,但不能在测试环境中工作。但果不其然,注销该文件中的console.log(SimpleLineIcons)会导致undefined

我用下面的代码消除了这个错误:

代码语言:javascript
复制
jest.mock('@expo/vector-icons', () => {
  const { View } = require('react-native');
  return {
    SimpleLineIcons: View,
    Ionicons: View,
  };
});

但它留下了一个问题:为什么模拟expo包会影响@expo/vector-icons包?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-11 01:02:47

Expo基本上有一个从SDK32内置的'expo-vector-icons‘模块。这就是为什么在通过Expo创建项目时不需要单独安装'expo-vector-icons‘模块,单独安装它们可能会导致冲突。

通过查看在preset文件中被忽略的转换模式,可以理解这一点。

expo/packages/jest-expo/jest-preset.js

代码语言:javascript
复制
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)',
];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57443897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档