Jest 单元测试 - SyntaxError:不能在模块外使用导入语句

Chr*_*rem 2 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';
Run Code Online (Sandbox Code Playgroud)

我的 Jest 配置package.json如下所示:

"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"
},
Run Code Online (Sandbox Code Playgroud)

我已经尝试了无数其他问题的例子,但我似乎无法解决这个问题。

编辑:为了记录,我正在使用 TypeScript

And*_*hiu 6

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

"jest": {
  // what you already have...
  transformIgnorePatterns: [
    "node_modules/(?!(a-module"
      + "|another-module"
      + "|yet-another-module"
      + ")/)",
  ]
}
Run Code Online (Sandbox Code Playgroud)

... where a-module, another-moduleandyet-another-module是您要忽略的模块。
如果您仔细查看错误,通常会找到导致该错误的模块的名称。但是,如果您无法弄清楚,请尝试使用editUser.vuehas 中导入的每个模块,然后将它们一个一个删除,直到找到最少数量的模块被忽略。

  • 在谷歌搜索了很多天并尝试了所有其他解决方案之后,除了这个之外没有其他解决方案。为什么这没有包含在“ts-jest”文档中? (2认同)