首页 > 解决方案 > 如何使用 Kitten UI 进行单元测试

问题描述

目前我正在使用 jest 对 react native 应用程序(expo CLI)进行单元测试,但是在测试渲染时,当我从 react-native 导入任何组件时,它完全没问题,但如果我从其他(例如 react-native-ui -小猫)。会有如下图所示的错误。有人可以帮助我提前谢谢!

这是我用 react-native 组件做快照的时候

当我做存在小猫 UI 组件的快照时

我在 package.json 中配置了“transformIgnorePatterns”但不工作

我的 package.json

  "jest": {
    "transform": {
      "^.+\\.(tsx|ts)?$": "ts-jest"
    },
    "preset": "jest-expo",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ]
  },
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|@ui-kitten/components|react-native-ui-kitten|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base)"
  ],
  "husky": {
    "hooks": {
      "pre-commit": "npm run lint",
      "pre-push": "npm run lint"
    }
  }

我的 jest.config.js

const {defaults} = require('jest-config');
module.exports = {
  // ...
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  preset: "jest-expo",
  // ...
};

我的 babel.config.js


const path = require('path');
const Config = require('./config');

// FIXME: Resolve `transform[stderr]: Could not resolve` command-line warnings.
// FIXME: Reproducible when starting with clearing cache (npm start -- -c)
//
// TODO: Framework path aliasing even not needed here. Replace?
// TODO: Replace nested package.json-s with aliases

const moduleResolverConfig = {
  root: path.resolve('./'),
  alias: {
    '@kitten/theme': path.resolve(Config.KITTEN_PATH, 'theme'),
    '@kitten/ui': path.resolve(Config.KITTEN_PATH, 'ui'),
    '@eva-design/eva': path.resolve(Config.MAPPING_PATH),
    '@eva-design/processor': path.resolve(Config.PROCESSOR_PATH),
  },
};

module.exports = function (api) {
  api.cache(true);

  const presets = [
    'babel-preset-expo',
  ];

  const plugins = [
    ['module-resolver', moduleResolverConfig],
  ];

  return { presets, plugins };
};

标签: reactjsreact-nativeunit-testingjestjsreact-native-ui-kitten

解决方案


确保忽略测试环境中的第 3 方模块。在 jest.config.js 中:

testPathIgnorePatterns: [
  '<rootDir>/node_modules',
],

此外,如果失败,还有一个众所周知的解决方法:

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|@ui-kitten)"
]

推荐阅读