简体   繁体   English

Jest 和 ES6 语法问题

[英]Issue with Jest and ES6 syntax

I have two test files that both use import .我有两个测试文件都使用import One of them passes, the other throws an error:其中一个通过,另一个抛出错误:

node_modules/@storybook/addon-docs/blocks.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import deprecate from 'util-deprecate';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';

I've got Jest configured like so:我已经像这样配置了 Jest:

module.exports = {
  collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: -10,
    },
  },
  moduleNameMapper: {
    '^@app/(.*)$': '<rootDir>/$1',
    '^@components/(.*)$': '<rootDir>/components/$1',
    '^@graphql/(.*)$': '<rootDir>/graphql/$1',
    '^@lib/(.*)$': '<rootDir>/lib/$1',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: [
    '<rootDir>/node_modules/',
  ],
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  },
  transformIgnorePatterns: ['/node_modules/'],
};

I'm completely baffled at how one file can run fine while another can't.我对一个文件如何可以正常运行而另一个文件不能正常运行感到非常困惑。 If someone could point me in the right direction that would be much appreciated.如果有人能指出我正确的方向,那将不胜感激。

Jest 27.xx has become stricter in it's implementation. Jest 27.xx 在它的实现上变得更加严格。

I had a similar situation when I used a markdown npm package.我在使用 markdown npm 包时也遇到过类似的情况。

Try changing:尝试改变:

transformIgnorePatterns: ['/node_modules/'],

to:到:

transformIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/node_modules/util-deprecate'],

Jest has this on their website where they explain how this issue can crop up. Jest 在他们的网站上有这个,他们解释了这个问题是如何突然出现的。

And here's an explanation of the issue copied verbatim with the important bits highlighted:这是对逐字复制的问题的解释,突出显示了重要的部分:

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled .有时会发生(尤其是在 React Native 或 TypeScript 项目中)第三方模块发布为untranspiled Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules , resulting in syntax errors.由于 node_modules 中的所有文件默认都不会被转换, Jest 不会理解这些模块中的代码,从而导致语法错误。 To overcome this, you may use transformIgnorePatterns to allow transpiling such modules.为了克服这个问题,您可以使用transformIgnorePatterns来允许转译此类模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM