首页 > 解决方案 > 无法在 Jest 中测试反应原生组件

问题描述

当我尝试运行此测试时,我收到了这个烦人的错误消息:

import React from "react";
import renderer from "react-test-renderer";

import App from "../App";

describe("<App />", () => {
  it("has 1 child", () => {
    const tree = renderer.create(<App />).toJSON();
    expect(tree.children.length).toBe(1);
  });
});

错误是:

 FAIL  __test__/App.test.js
  ✓ works (4ms)
  <App />
    ✕ has 1 child (17ms)

  ● <App /> › has 1 child

    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

我在这里找到了解决方案https://github.com/expo/expo/issues/5268但那个对我不起作用。我的package.json样子是这样的:

  "devDependencies": {
    "@types/react": "^16.8.23",
    "@types/react-native": "^0.57.65",
    "babel-preset-expo": "^6.0.0",
    "jest": "^24.8.0",
    "jest-expo": "^34.0.0",
    "react-dom": "^16.8.6",
    "react-test-renderer": "^16.8.6"
  },
  "jest": {
    "preset": "jest-expo",
    "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)"
    ]
  },

标签: reactjsunit-testingreact-nativejestjs

解决方案


推荐阅读