【问题标题】:JEST config testing node_module even if its disabled?JEST 配置测试 node_module 即使它被禁用?
【发布时间】:2021-07-17 05:07:14
【问题描述】:

我正在使用 Jest 向现有代码库添加测试。这是我得到的错误

   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:
     • 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:

    /home/me/app/node_modules/register-service-worker/index.js:32
    export function register (swUrl, hooks) {
    ^^^^^^

    SyntaxError: Unexpected token export

我不明白如何正确配置transformIgnorePatterns? 但是我的 jest.config.js 设置为忽略 node_modules ? 查看react example,但无法真正理解它如何转化为我的东西......?我在 VueJS 项目中,没有使用 typescript。


module.exports = {
  preset: "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
  transformIgnorePatterns: ["/node_modules/"],
  // setupFiles: [
  //   "./tests/unit/setup.ts",
  // ],
};

【问题讨论】:

  • 我的建议是,为register-service-worker 创建一个mock。无论如何,您不应该真正测试 3rd 方代码
  • 你见过this
  • @Phil - OP 没有尝试测试第三方代码,他们想知道为什么 node_modules 没有被忽略。为该服务人员创建一个模拟只会导致 node_modules 中的其他内容试图被转译。
  • @Adam 我的意思是第 3 方代码包含在测试中,这是您无法控制的。 IMO,应控制合作者
  • @Adam 不幸的是,链接的建议没有帮助。同样的错误。我会尝试模拟它,因为无论如何我都需要学习...但是如果有人知道如何阻止 Jest 调查 node_modules 在我的情况下,请告诉我。谢谢:)

标签: javascript node.js vue.js jestjs


【解决方案1】:

看来扩展jest.config.js解决了上面的错误。

  "transform": {
    ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
  },

我现在有一个不同的错误,但现在更具体的是 Vue。

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 2019-07-16
    • 2018-09-11
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2021-06-12
    相关资源
    最近更新 更多