开玩笑抛出错误,“transformIgnorePatterns 不起作用”

时间:2021-04-19 17:39:19

标签: jestjs

我正在使用 Jest 测试框架为我的 JavaScript/React 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:

    C:\Users\{user}\{project}\app\node_modules\react-date-picker\node_modules\react-calendar\dist\Calendar.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.react-calendar {

错误来自 node_modules 文件夹中的包,\react-date-picker。

为了解决这个问题,我改变了 jest.config.js 文件如下。

const esModules = [ 'react-date-picker'].join('|');
module.exports = {
    verbose: true,
    transformIgnorePatterns: [`/node_modules/(?!${esModules})`]
};

这是“npm run unit:test”的命令

"jest --watchAll --testPathPattern=tests/unit --config jest.config.js",

当我再次运行测试时,我仍然遇到同样的错误。我该如何解决?

1 个答案:

答案 0 :(得分:0)

这里有一个非常相似的情况,他设法通过将 "allowJs": true 添加到每个 compilerOptionslib/apptsconfig.spec.json(或者也可以添加到根 {{ 1}}) 除了设置 tsconfig.json

查看来源:https://github.com/nrwl/nx/issues/812