Cannot test Vue component with Jest: Syntax error - Unexpected identifier

Project is created with @vue/[email protected]. This is package.json

"scripts": {
  "serve": "vue-cli-service serve",
  "build": "vue-cli-service build",
  "lint": "vue-cli-service lint",
  "test": "npm run lint && npm run test:unit",
  "test:unit": "jest --no-cache"
},
"dependencies": {
  "core-js": "^2.6.5",
  "vue": "^2.6.10"
},
"devDependencies": {
  "@vue/cli-plugin-babel": "^3.6.0",
  "@vue/cli-plugin-eslint": "^3.6.0",
  "@vue/cli-service": "^3.6.0",
  "@vue/eslint-config-standard": "^4.0.0",
  "babel-eslint": "^10.0.1",
  "babel-jest": "^24.7.1",
  "eslint": "^5.16.0",
  "eslint-plugin-vue": "^5.0.0",
  "jest": "^24.7.1",
  "vue-jest": "^3.0.4",
  "vue-template-compiler": "^2.5.21"
},
"jest": {
  "transform": {
    "^.+\\.js$": "babel-jest",
    "^.+\\.vue$": "vue-jest"
  }
}

This is my test

import Item from '../Item.vue'

describe('Item.vue', () => {
  test('sanity test', () => {
    console.log(Item)
  })
})

with the component Item.vue being

<template>
  <div>
    Item
  </div>
</template>

and this is the result

enter image description here

I get the error on the import statement. I thought this would be dealt by using the jest transformers, but it is not. What else do i need to add to pass the tests? The project url is this.

Upvotes: 0

Views: 1610

Answers (2)

LLucas
LLucas

Reputation: 83

You've never defined any Item component. The only file you have in your project is Item.vue which contains only a template, there is no way for vuejs to import 'Item' since you've never declared your template as 'Item'.

You should have a look to the VueJS Documentation about components ! In the first example you can see how the binding classname-template is done.

Then you will be able to import 'Item' from Item.vue.

Upvotes: 0

Seb Kelly
Seb Kelly

Reputation: 91

I presume you got this for reading the vue testing book by Edd Yerburgh. The code for which is available at https://www.manning.com/books/testing-vue-js-applications.

I had the same problem, and by checking the difference between my code and their chapter 3 code found the fix which was that the babel.config.js requires adding:

process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true
process.env.VUE_CLI_BABEL_TARGET_NODE = 'node'

module.exports = {
  presets: [
    '@vue/app'
  ]
}

Good luck!

Upvotes: 1

Related Questions