【问题标题】:create-react-app and jest - Cannot use import statement outside a modulecreate-react-app 和 jest - 不能在模块外使用 import 语句
【发布时间】:2021-05-09 10:56:41
【问题描述】:

我正在使用 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() });

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

【问题讨论】:

    标签: jestjs babeljs create-react-app


    【解决方案1】:

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

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

    来自我的package.json(虽然 Enzyme instructs 在使用 Jest 时包含它)。

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2021-04-22
      相关资源
      最近更新 更多