我正在尝试使用 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-module
和 yet-another-module
是您想要忽略的模块。如果您仔细查看错误,您通常会找到导致它的模块的名称。但是,如果您无法弄清楚,请尝试使用
editUser.vue
中导入的每个模块has 然后将它们一一删除,直到找到要忽略的最少模块。
关于javascript - Jest 单元测试 - SyntaxError : Cannot use import statement outside a module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63389757/