Jest transformIgnorePatterns不起作用

问题描述 投票:12回答:3

[我花了很长的时间查看与此有关的其他问题,并查看了Github上的其他项目,但似乎没有一个答案对我有用。

我正在项目中加载第三方库,并且在运行Jest测试时收到错误消息

export default portalCommunication;
^^^^^^

SyntaxError: Unexpected token export

> 1 | import portalCommunication from 'mathletics-portal-communication-service';

我已经尝试通过多种方式来更新我的Jest配置,以使其能够转换为该库,但是我总是遇到相同的错误。

这是我当前的jest.config.js文件:

module.exports = {
    moduleNameMapper: {
        '\\.(css|scss)$': 'identity-obj-proxy',
        '\\.svg$': '<rootDir>/test/mocks/svg-mock.js'
    },
    setupFiles: ['./test/test-setup.js'],
    transformIgnorePatterns: [
        '<rootDir>/node_modules/(?!mathletics-portal-communication-service)'
    ]
};

我还尝试添加transform属性以针对此mathletics-portal-communication-service目录运行babel-jest。

请帮助!

javascript reactjs jest babel-jest
3个回答
4
投票

作为目前的解决方法,我已将配置更改为使用moduleNameMapper选项来加载该库的模拟类。我本来希望使用transformIgnorePatterns代替,所以仍然会感激任何想法。

新配置:

module.exports = {
    moduleNameMapper: {
        '\\.(css|scss)$': 'identity-obj-proxy',
        '\\.svg$': '<rootDir>/test/mocks/svg-mock.js',
        'mathletics-portal-communication-service': '<rootDir>/test/mocks/mathletics-portal-communication-service-mock.js'
    },
    setupFiles: ['./test/test-setup.js']
};

3
投票

直到我将.babelrc更改为babel.config.js之前,transformIgnorePatterns才对我有用,就像这样:

module.exports = {
    "presets": [
        "@babel/preset-env"
    ]
};

如在此评论上所见:https://github.com/facebook/jest/issues/6229#issuecomment-403539460


0
投票

Jest默认安装babel-jest。我有一个与此类似的问题(我的node_modules文件夹中的一个文件夹包含一个传播运算符)。我需要正确设置babel并在transformIgnorePatterns中添加package.json声明,才能在node_modules文件夹中转换特定的依赖项:

package.json

...
  "devDependencies": {
    ...
    "@babel/preset-env": "^7.6.3",
    ...
  }
...
  "jest": {
    "moduleFileExtensions": [
      "js"
    ],
    "setupFilesAfterEnv": [
      "@testing-library/jest-dom/extend-expect"
    ],
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.svelte$": "jest-transform-svelte"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(indent-string/index(.js)?))"
    ]
  },
...

如果您不需要声明任何转换(我必须转换.svelte文件),则可能可以完全忽略transform部分,并且babel-jest默认会转换.js文件-因为我已经声明了一个转换,我认为它覆盖了默认值,因此我也必须显式声明js转换。

["node_modules/(?!(indent-string/index(.js)?))"告诉玩笑不要在node_modules期望indent-string/index.js中传递任何东西。

.babel-config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};
© www.soinside.com 2019 - 2024. All rights reserved.