【问题标题】:ts-jest cannot run testing on imported ES6 modulests-jest 无法在导入的 ES6 模块上运行测试
【发布时间】:2017-08-09 02:11:08
【问题描述】:

我在我的 Typescript 应用程序中使用已编译的 ES6 库。测试失败并出现错误

TypeError:无法读取未定义的属性“PropTypes”

它抱怨的模块将react 导入为

import React from 'react';

如果我把它改成

import * as React from 'react';

然后它将编译并运行良好。这是我的package.jsonjest 配置:

"jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ],
    "verbose": true,
}

这是我的tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true,
        "preserveConstEnums": true,
        "removeComments": true,
        "noImplicitAny": false,
        "moduleResolution": "node",
        "noUnusedParameters": true
    },
    "include": [
        "./src/**/*"
    ],
    "filesGlob": [
        "**/*.ts",
        "**/*.tsx"
    ],
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts",
        "typings/index.d.ts"
    ]
}

我在这里搞砸了什么配置?

【问题讨论】:

    标签: javascript reactjs typescript jestjs


    【解决方案1】:

    then it will compile and run fine.

    这就是 TypeScript 要走的路。 import * as React from "react".

    【讨论】:

    • 它迟早会坏掉。如果可能的话,应该避免它。 Webpack 和 SystemJS 启用了import React from "react",因此任何使用这两种工具的人都应该更喜欢使用该语法来导入 非命名空间 import github.com/nodejs/node-eps
    • @AluanHaddad 不是import React from "react" 一个不行当现在使用raw TypeScript transpile -&gt; run in node 时?
    • @basarat,这是我通过npm 安装的模块。 Typescript 应该可以导入 JS 模块。事实上确实如此。应用程序编译良好。这是失败的开玩笑测试。
    • @Kousha 没错。因为该代码不适用于标准编译到节点。使用* as React?
    • @basarat,这也是我通过npm install 使用的一个模块,然后在我的 .tsx 文件中使用了一个 React 组件。该错误与 React 组件 FROM 模块有关。除非我针对该模块打开 PR 并强制作者使用 * as React,否则您的解决方案将无济于事。
    猜你喜欢
    • 2020-02-10
    • 2023-04-02
    • 2023-03-28
    • 2018-09-14
    • 2019-02-09
    • 2020-09-03
    • 2017-09-08
    • 2020-10-01
    • 2021-05-30
    相关资源
    最近更新 更多