Jest + Vue3 + @Vueform/slider "SyntaxError: Cannot use import statement outside a module"

Viewed 820

I'm using Jest as a test runner in a Vue 3 project that makes use of the @vueform slider plugin:

https://github.com/vueform/slider

the code in @vueform/slider/dist/slider.js:1 tiggers a "SyntaxError: Cannot use import statement outside a module" error.

I've tried adding a "transformIgnorePatterns" entry in the package.json's Jest configuraiton:

"jest": {
  "testEnvironment": "jsdom",
  "moduleFileExtensions": [
    "js",
    "json",
    "vue"
  ],
  "transform": {
    "^.+\\.(js|jsx)$": "babel-jest",
    "^.+\\.(vue)$": "vue3-jest"
  },
  "transformIgnorePatterns": ["/node_modules/(?!@vueform/slider/)", "node_modules/(?!@vueform/)"]
}

I Also added "type": "module" to package.json

And tried changing

import SliderPrice from "@vueform/slider" 

to

const SliderPrice = require("@vueform/slider")

Still getting the same error!

Any ideas how I can solve this issue? I can't test anything with Jest until this error gets sorted.

Edit:

I forgot to add this: Intially, the error message details included the entire (minimized) slider.js file. After adding "type": "module" to package.json the details now include just this line:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { toRefs as t, ref as e, computed as r, reactive as n, onMounted as i, onUnmounted as o, watch as a, openBlock as s, createBlock as l, mergeProps as u } from "vue";

Edit 2:

My babel config is in a .babelrc file:

{
  "presets": ["@babel/preset-env"]
}
  • Vue is the front end setup within a Laravel application, but the webpack.mix.js configuration file doesn't use babel.

Edit 3:

After a few more hours of playing around with the settings, I believe that this is Babel related: If I delete my .babelrc file then I start getting the "SyntaxError: Cannot use import statement outside a module" error for my own .vue files. This shows that with the .babelrc file, my ES6 javascript files are being transformed to ES5.

So the Vue plugins, like @vueform/slider/ are NOT being transformed to ES5 by Babel, even though the correct path is defined in "transformIgnorePatterns"

1 Answers

For vue3 and 2 (I didn't test it on 2 but should work)

npm i -D @babel/preset-env babel-jest

babel.config.js

{
  "presets": ["@babel/preset-env"]
}

I have had issues also with vue files. Below my configuration works ok.

npm i -D @vue/vue3-jest # or 2 if you are on second version

jest.config.js

export default {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.[t|j]sx?$': 'babel-jest',
    '^.+\\.vue$': '@vue/vue3-jest',
  },
}

Related