不使用 Jest 和 Typescript 导入的导入

mer*_*ort 9 typescript reactjs jestjs babeljs enzyme

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

开玩笑的配置文件

/* 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"
  }
};
Run Code Online (Sandbox Code Playgroud)

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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Art*_*hle 0

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

BTWnode是默认值,因此您无论如何都可以忽略该选项

也许尝试一下这是否可以解决问题: testEnvironment=jsdom

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