首页 > 解决方案 > create-react-app 和 jest - 不能在模块外使用 import 语句

问题描述

我正在使用 create-react-app。从 CLI运行jest会导致此错误(尽管在 VS Code 中它在我的测试文件中显示我的测试通过了):

(base) ➜  component-library git:(setup) ✗ jest
 FAIL  src/App.test.js
  ● 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:

    /Users/Me/go/src/gitlab.com/tensile-payments/component-library/src/setupTests.js:5
    import '@testing-library/jest-dom';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)

我的 setupTests.js 文件如下所示:

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

Enzyme.configure({ adapter: new Adapter() });

我从另一个问题的回答中了解到,Jest Babel 在运行测试之前转换文件,这应该摆脱这些导入语句。我没有弹出,所以没有更改 babel 配置。其他人遇到的问题是节点模块没有被转换,因为默认配置将它们排除在外,但这个错误不是来自节点模块。我怎样才能解决这个问题?

标签: jestjsbabeljscreate-react-app

解决方案


npm run test我通过使用而不是运行测试来修复它jest,以及删除

  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>src/setupTests.js"
    ]
  }

来自我的package.json(尽管 Enzyme指示在使用 Jest 时包含它)。


推荐阅读