笑话测试失败,没有元数据

时间:2020-09-22 21:04:55

标签: reactjs typescript jestjs babel-jest ts-jest

具有因特定错误消息而失败的单元测试。

 Test suite failed to run

    Failed to get mock metadata: <path-to-project>/node_modules/lodash/_freeGlobal.js

    See: https://jestjs.io/docs/manual-mocks.html#content

问题的根源似乎是应用程序代码中的lodash/isEmpty用法。依存关系最终缩小为导出_freeGlobal.js对象的global。 jest(使用jest-mocks库)无法获取该对象的元数据,因为它无法识别类型。

问题:我有办法模拟全局对象或使Jest正确模拟lodash返回的global吗?

我完全知道问题发生在哪里。

  • 开玩笑地遍历我的打字稿文件中的每个导入
  • 确定每个模块的最后一级,
  • 通过玩笑模拟来模拟它们
  • 在这里开玩笑tries to getMetadata
  • 作为元数据的一部分,它尝试获取type name here
  • 并且由于Object.prototype.toString.call(global)发出[object Window],因此它无法检测到typeName window 错误。

环境

"jest": "24.9.0",
"jest-cli": "24.9.0",
"jest-dom": "4.0.0",
"ts-jest": "24.2.0",
"@types/jest": "24.0.25",
"babel-jest": "24.9.0",

最佳配置:

"jest": {
  "automock": true,
  "preset": "ts-jest/presets/js-with-babel",
  "testEnvironment": "jsdom",
  "roots": [
    "./app/cdap/"
  ],
  "modulePaths": [
    "./app/cdap/"
  ],
  "modulePathIgnorePatterns": [
    "./app/cdap/components/AbstractWidget/SchemaEditor/Context/__tests__/schemas.js",
    "./app/cdap/components/AbstractWidget/SchemaEditor/Context/__tests__/data"
  ],
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/lodash/isEmpty",
    "<rootDir>/node_modules/lodash/round",
    "<rootDir>/node_modules/lodash/cloneDeep",
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom"
  ],
  "moduleNameMapper": {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    ".scss$": "<rootDir>/__mocks__/styleMocks.js",
    "/^components/": "<rootDir>/app/cdap/components",
    "/^services/": "<rootDir>/app/cdap/services",
    "/^api/": "<rootDir>/app/cdap/api",
    "^lib": "<rootDir>/../lib",
    "^mocks": "<rootDir>/__mocks__"
  },
  "globals": {
    "ts-jest": {
      "babelConfig": {
        "plugins": [
          "@babel/plugin-transform-modules-commonjs"
        ]
      }
    }
  }
}

注意: 尝试过建议from other thread 。当我继续向unmockedModulePatterns添加特定的lodash模块时,最终我的模块被嘲笑了,所有的测试都失败了。

"unmockedModulePathPatterns": [
   "<rootDir>/node_modules/lodash/isEmpty",
   "<rootDir>/node_modules/lodash/round",
   "<rootDir>/node_modules/lodash/cloneDeep",
   "<rootDir>/node_modules/react",
   "<rootDir>/node_modules/react-dom"
],

0 个答案:

没有答案