Vue Test Utils 单元测试报错:SyntaxError: Cannot use import statement outside a module 解决办法

在使用 Jest 和 @vue/test-utils 对 Vue 组件进行单元测试时,你可能会遇到如下错误信息:

SyntaxError: Cannot use import statement outside a module

例如:

D:\ImouStorePC\node_modules\@babel\runtime\helpers\esm\slicedToArray.js:1
({'Object.<anonymous>':function(module,exports,require,__dirname,__filename,global,jest){import arrayWithHoles from './arrayWithHoles.js';
                                                                                             ^^^^^^

SyntaxError: Cannot use import statement outside a module



  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at components/TabsBar.vue:707:98
  at Object.<anonymous> (components/TabsBar.vue:775:3)
  at Object.<anonymous> (components/__test__/TabsBar.test.js:2:1)

错误原因

这个错误是因为在你的测试文件中使用了 import 语句,而 import 语句是 ES6 的模块语法,Node.js 默认不支持。

解决方法

为了解决这个问题,你可以使用 Babel 来转换你的测试文件。

  1. 安装依赖

npm install --save-dev @babel/core @babel/preset-env babel-jest


2. **创建 Babel 配置文件**

在项目根目录下创建一个 `.babelrc` 文件,并添加以下内容:

```json
{
  'presets': ['@babel/preset-env']
}
  1. 配置 Jest

    在你的 package.json 文件中添加以下配置,告诉 Jest 使用 babel-jest 来转换测试文件:

    {
      'jest': {
        'transform': {
          '^.+\.js$': 'babel-jest'
        }
      }
    }
    
  2. 重新运行测试

    完成以上步骤后,重新运行你的测试命令,应该就不会再报错了。

Vue Test Utils 单元测试报错 SyntaxError: Cannot use import statement outside a module 解决办法

原文地址: http://www.cveoy.top/t/topic/fNzx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录