使用 Typescript 和 Jest 响应本机测试

时间:2021-06-07 18:33:53

标签: typescript react-native jestjs

我正在尝试使用 react-native/expo 和 typescript 开始测试。我已经使用世博会的基本打字稿模板创建了一个应用程序。

为了开始测试,我遵循了关于 testing with Jest 的博览会文档。我已添加 jest-exporeact-test-renderer 作为开发依赖项,并根据文档更新了 package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    ...
    "test": "jest"
  },
  "dependencies": {
    "expo": "~41.0.1",
    "expo-status-bar": "~1.0.4",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-41.0.0.tar.gz",
    "react-native-web": "~0.13.12"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@types/jest": "^26.0.23",
    "@types/react": "~16.9.35",
    "@types/react-native": "~0.63.2",
    "@types/react-test-renderer": "^17.0.1",
    "jest-expo": "^41.0.0",
    "react-test-renderer": "^17.0.2",
    "typescript": "~4.0.0"
  },
  "private": true,
  "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/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ]
  }
}

这是测试,App.test.tsx:

import renderer from 'react-test-renderer';
import App from "../App";
import React from "react";

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

在编辑器 (Webstorm) 中抛出 2 个错误:

  1. tree Object is possibly 'null'.
  2. Property 'children' does not exist on type 'ReactTestRendererJSON | ReactTestRendererJSON[]'. Property 'children' does not exist on type 'ReactTestRendererJSON[]'

而且,当我运行测试时,它会为 <App />

抛出一个不同的错误 <块引用>

renderer.create(<App />).toJSON()

<块引用>

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件)但得到:对象。

你能帮我看看我在这里遗漏了什么吗?如何使用 typescript 和 jest 测试 react native?

1 个答案:

答案 0 :(得分:0)

Expo 的 Jest 预设似乎存在错误/问题,因为我发现有一个与错误相关的开放 GitHub issue

为了按照 GitHub 的回答解决这个问题,就像 Kipnoedels 指出的那样,我不得不在 package.json 的 jest 配置中添加这个:

"moduleFileExtensions": ["ts", "tsx", "js"]

所以,package.json 看起来有点像这样:

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    ...
    "test": "jest"
  },
  "dependencies": {
    ..
  },
  "devDependencies": {
    ...
  },
  "private": true,
  "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/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ],
    "moduleFileExtensions": ["ts", "tsx", "js"]
  }
}