javascript - Jest 单元测试 - SyntaxError : Cannot use import statement outside a module

标签 javascript unit-testing vue.js jestjs

我正在尝试使用 Jest 在 Vue 中设置单元测试。但是,我收到此错误:

● Test suite failed to run
...
SyntaxError: Cannot use import statement outside a module

 >1 | import editUser from '@/components/forms/editUser.vue';
    | ^
  2 | import TestComponent from '@/pages/user/UserMyProfile.vue';
  3 | import { shallowMount } from '@vue/test-utils';
  4 | import { expect } from 'chai';
  5 | import 'jest';
我在 package.json 中的 Jest 配置看起来像这样:
"jest": {
    "moduleFileExtensions": [
        "js",
        "ts",
        "json",
        "vue"
    ],
    "transform": {
        ".*\\.(vue)$": "vue-jest",
        "^.+\\.tsx?$": "ts-jest"
    },
    "testURL": "http://localhost/",
    "moduleNameMapper": {
        "^@/(.*)$": "<rootDir>/src/$1"
    },
    "modulePaths": [
        "<rootDir"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "preset": "@vue/cli-plugin-unit-jest/presets/no-babel"
},
我已经尝试了无数其他问题的例子,但我似乎无法解决这个问题。
编辑:为了记录,我正在使用 TypeScript

最佳答案

问题是您正在使用的某些 (node_) 模块需要被转译,而有些则不需要。因此,您需要使用此语法,直到找到需要忽略的语法:

"jest": {
  // what you already have...
  transformIgnorePatterns: [
    "node_modules/(?!(a-module"
      + "|another-module"
      + "|yet-another-module"
      + ")/)",
  ]
}
...在哪里 a-module , another-moduleyet-another-module是您想要忽略的模块。
如果您仔细查看错误,您通常会找到导致它的模块的名称。但是,如果您无法弄清楚,请尝试使用 editUser.vue 中导入的每个模块has 然后将它们一一删除,直到找到要忽略的最少模块。

关于javascript - Jest 单元测试 - SyntaxError : Cannot use import statement outside a module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63389757/

相关文章:

javascript - socket.io (nodejs) 发出回调是否会通过在回调完成期间阻塞服务器来影响服务器性能?

javascript - 输出总是给出 []

unit-testing - 如何通过 mat-dialog-close 或其他方式对 MatDialog 关闭进行单元测试

python - 为什么在 Jupiter Notebook 上执行单元测试时会出现 AttributeError?

javascript - 在 vue js 中加载组件之前渲染图像

javascript - 这个 CompareAmounts 函数到底是做什么的? (分析)

javascript - 双击 HTML 按钮不会在代码隐藏文件中创建事件处理程序

python - 我可以在 Python unittest 中对测试方法和/或测试类进行分组吗

javascript - 如何将 JS .sort 添加到 Vue 方法中

javascript - 返回到之前工作的组件会出现白页