【问题标题】:Imports not importing using Jest and Typescript不使用 Jest 和 Typescript 导入的导入
【发布时间】:2019-05-20 03:18:32
【问题描述】:

我正在使用 Jest、Enzyme 和 Typescript,但由于某些原因,某些导入无法正常工作......它们是未定义的。例如,我在一个文件中有import ReactMarkdown from 'react-markdown';,当我运行测试时,我得到Cannot read property 'createElement' of undefined for ReactMarkdown。下面是配置文件

jest.config.js

/* tslint:disable */

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js"
  ],
  transform: {
    "^.+\\.tsx?$": "ts-jest",
    "^.+\\.svg$": "jest-svg-transformer"
  },
  testMatch: [
    "**/*.(test|spec).(ts|tsx)"
  ],
  globals: {
    "ts-jest": {
      babelConfig: true,
      tsConfig: "jest.tsconfig.json"
    }
  },
  coveragePathIgnorePatterns: [
    "/node_modules/",
    "enzyme.js"
  ],
  setupTestFrameworkScriptFile: "<rootDir>/enzyme.js",
  coverageReporters: [
    "json",
    "lcov",
    "text",
    "text-summary"
  ],
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/mocks.js",
    "\\.(css|less|scss)$": "<rootDir>/__mocks__/mocks.js"
  }
};

jest.ts.config.json

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "commonjs",
    "target": "esnext",
    "jsx": "react",
    "sourceMap": false,
    "experimentalDecorators": true,
    "noImplicitUseStrict": true,
    "removeComments": true,
    "moduleResolution": "node",
    "lib": [
      "es2017",
      "dom"
    ],
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "out",
    ".next"
  ]
}

【问题讨论】:

  • 是不是因为你的tsconfig.json里需要allowSyntheticDefaultImports:true
  • 不,我的 tsconfig 中有这个
  • @mergesort 你找到解决这个问题的方法了吗?
  • 显示你的 tsconfig。根据我的经验,大多数(如果不是全部)导入问题都源于错误的 tsconfig。 tsconfig 允许您定义诸如路径别名和 baseUrl 之类的东西,它们可以提供更好的路径,但不能与其他 JS 技术很好地配合。
  • 你使用哪个版本的 react-markdown?

标签: reactjs typescript jestjs babeljs enzyme


【解决方案1】:

createElement 是全局 document 变量的方法。 document 在浏览器中运行时在 JavaScript 中可供我们使用,但在 node 中不可用,因此当某些东西试图在节点单元测试环境中运行 document.createElement() 时,document 未定义的原因。

JSDOM 是一个库,它将创建一个假的 documentwindow 全局变量,可用于单元测试场景,例如您尝试实现的场景。因此,在您的测试环境中实现 JSDOM,尤其是引发错误的 ReactMarkdown 组件,可以帮助您解决这个问题。

详细的描述可以在Testing With Node, Jest, and JSDOM阅读

【讨论】:

    【解决方案2】:

    你确定testEnvironment=node 是正确的吗?因为 Node 中没有 document 并且会解释错误信息。

    顺便说一句,node 是默认值,所以无论如何你都可以省略该选项?

    如果这能解决问题,不妨试试: testEnvironment=jsdom

    您可能会考虑使用这个库,它可以让您立即工作,而无需自己完成整个设置: https://www.npmjs.com/package/jest-environment-enzyme

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2019-05-17
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多