首页 > 解决方案 > 在 babel 中使用 jest

问题描述

我仅将 react-scripts 用于测试,并希望摆脱它。我试图重新创建test脚本,但它没有按我预期的方式工作。

这是我的jest.config.js

module.exports = {
  transform: {
    "^.+\\.(j|t)sx?$": "babel-jest",
  },
  moduleNameMapper: {
    "\\.(css)$": "identity-obj-proxy",
  },
};

.babelrc

{
  "presets": [
    "@babel/preset-react",
    [
      "@babel/preset-env",
      {
        "modules": false
      }
    ],
    ["@babel/preset-typescript", { "onlyRemoveTypeImports": true }]
  ],
  "plugins": [
    [
      "transform-rename-import",
      {
        "replacements": [
          {
            "original": "^(.+?)\\.svg$",
            "replacement": "$1.js"
          }
        ]
      }
    ]
  ],
  "ignore": [
    "**/*.svg"
  ]
}

当我运行时jest,我收到此错误:

 ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/aironside@ant.local/Documents/microfrontends_libs/react-components/src/lib/components/molecules/empty/__specs__/Empty.spec.tsx:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

知道我在这里缺少什么吗?

标签: javascriptreactjsjestjsbabeljsbabel-jest

解决方案


推荐阅读