Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SyntaxError: Cannot use import statement outside a module" when running a Jest test with Vue Js

I followed this tutorial https://frontstuff.io/build-your-first-vue-js-component to build a vue js component. I then followed this tutorial https://frontstuff.io/unit-test-your-first-vuejs-component to unit test the component. The unit test fails at the import statement on the component and returns this error:

● Test suite failed to run

C:\Users\SHINIGAMI-ALFSABAH\Documents\Workspace\Dev\Vue\star-rating\node_modules\vue-awesome\icons\star.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                         ^^^^^^

SyntaxError: Cannot use import statement outside a module

  12 | 
  13 | <script>
> 14 |     import 'vue-awesome/icons/star'
     | ^
  15 |     import Icon from 'vue-awesome/components/Icon'
  16 | 
  17 |     export default {

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at src/components/Rating.vue:14:1
  at Object.<anonymous> (src/components/Rating.vue:67:3)

Any help will be appreciated.

like image 655
Layo Folaranmi Avatar asked Feb 15 '20 09:02

Layo Folaranmi


2 Answers

I found an answer on SO from a previous similar question Unexpected token 'import' error while running Jest tests?

Basically I had to change my transformIgnorePatterns array in my jest config from:

transformIgnorePatterns: ["/node_modules/"],

to

transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],

making sure jest compiles 'vue-awesome' module to use in the test.

like image 153
Layo Folaranmi Avatar answered Oct 16 '22 13:10

Layo Folaranmi


What I did was I installed the dependencies needed for vue and jest to work together, then I created a config file for babel and jest.

//Installing dependencies for jest and vue js
npm i -D @vue/test-utils jest vue-jest @vue/babel-preset-app babel-core@^7.0.0-bridge.0

//jest.config.js
module.exports = {
    moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
    transform: {
        ".*\\.(vue)$": "vue-jest",
        "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
    }
};

//babel.config.js
module.exports = {
    presets: [
        '@vue/app'
    ]
};

like image 37
Laurenze Castro Avatar answered Oct 16 '22 13:10

Laurenze Castro