Robert Yao
Robert Yao

Reputation: 19

Test Vue with Jest fail, Jest encountered an unexpected token, SyntaxError: Unexpected token import

I test Vue project with jest, bug I got errors says:

Jest encountered an unexpected token and SyntaxError: Unexpected token import

here is my jest.conf.js, I set the "transorm" option with babel-jest and vue jest, but I still got the error says can't transorm the es6 syntax

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname, '../../'),
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
  },
  testPathIgnorePatterns: [
    '<rootDir>/test/e2e'
  ],
  snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
  setupFiles: ['<rootDir>/test/unit/setup'],
  coverageDirectory: '<rootDir>/test/unit/coverage',
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/main.js',
    '!src/router/index.js',
    '!**/node_modules/**'
  ]
}

and here is the .babelrc config:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime",
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "~node_modules/modeling-theme-element/lib"
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "jest",
        "stage-2"
      ],
      "plugins": [
        [
          "dynamic-import-node",
          {
            "root": [
              "./src"
            ],
            "alias": {
              "@": "./src"
            }
          }
        ]
      ]
    }
  }
}

Upvotes: 2

Views: 4581

Answers (2)

Pratik
Pratik

Reputation: 1061

Most probably when updating package dependency, "babel-core" dependency may have been updated to 6.xx.x, it should be "7.0.0-bridge.0" for jest to work.

Reference: https://github.com/vuejs/vue-cli/issues/1879#issuecomment-412300256 https://github.com/vuejs/vue-cli/issues/1879#issuecomment-435194932

Upvotes: 2

Michael
Michael

Reputation: 46

I had a similar problem and "babel-plugin-transform-es2015-modules-commonjs" is working for me

npm i -D babel-plugin-transform-es2015-modules-commonjs

.babelrc config "plugins":["transform-es2015-modules-commonjs"]

Upvotes: 3

Related Questions