Jest单元测试 - SyntaxError:无法在模块外部使用import语句

5
我将尝试使用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。

1个回答

7
问题在于你正在使用的一些(node_)模块需要转译,而有些则不需要。因此,你需要尝试以下语法,直到找到那些需要被忽略的模块:
"jest": {
  // what you already have...
  transformIgnorePatterns: [
    "node_modules/(?!(a-module"
      + "|another-module"
      + "|yet-another-module"
      + ")/)",
  ]
}

......其中a-moduleanother-moduleyet-another-module是您想要忽略的模块。
如果你仔细看错误信息,通常会找到导致它发生的模块名称。但是,如果您无法确定,请尝试使用editUser.vue中导入的每个模块,然后逐个删除,直到找到要忽略的最小模块数。


3
除了这个解决方案,经过多天的谷歌搜索和尝试所有其他解决方案,没有其他东西起作用。为什么ts-jest文档中没有包含这个呢? - pizzae
更具体地说,这种方法是在node_modules目录中转换TypeScript npm依赖项的双重忽略。就像“忽略所有,但是…” 默认情况下,jest似乎假定每个导入的npm包都是纯JavaScript,并且不需要进行转换。当然,这节省了很多时间。 - rfinster
1
除了答案外,这是官方 Jest 文档链接 中有关 transformIgnorePatterns Jest 配置选项的说明。 这是使用示例 - Valentine Shi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接