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

时间:2020-08-13 07:00:23

标签: 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

1 个答案:

答案 0 :(得分:2)

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

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

...其中a-moduleanother-moduleyet-another-module是您要忽略的模块。
如果仔细查看错误,通常会找到引起该错误的模块的名称。但是,如果您无法解决问题,请尝试使用editUser.vue中导入的每个模块,然后将它们一个一个地删除,直到找到要忽略的最小模块数量。

相关问题