Jest tests can't process import statement

Version
3.0.0-rc.2
Reproduction link
https://github.com/ijdickinson/vue-cli-jest-problem
Steps to reproduce
This is a similar problem to 1475, but I can't find a way to resolve it. I created a new app with vue-cli, selecting Jest tests. I added a simple POJO (src/models/model.js) and a test for it (tests/model.spec.js).
To repro the problem, just npm run test:unit
What is expected?
Tests to pass, or at least run
What is actually happening?
$ npm run test:unit

><EMAIL_ADDRESS>test:unit /home/ian/workspace/project/test-application
> vue-cli-service test:unit

 FAIL  tests/unit/model.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://facebook.github.io/jest/docs/en/configuration.html

    Details:

    /home/ian/workspace/project/test-application/tests/unit/model.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.promise";
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:402:17)

 PASS  tests/unit/HelloWorld.spec.js

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.427s
Ran all test suites.
 ERROR  jest exited with code 1.

I was able to fix this issue by adding the following to the jest.config.js transform section:
'^.+\\.js$': 'babel-jest',

@minorgod Thanks, I confirm that this does indeed fix my problem.
So, should it be added to the standard template for jest.config.js? Or is it something that just needs to be mentioned in the docs?

This looks like a bug, since it's done here.

Adding '^.+\\.js$': 'babel-jest' does fixes it, I was facing the same problem with vue-cli: 3.0.0-rc.3.
Just a reminder that it should be placed in the end of the transform object, right after '^.+\\.tsx?$': 'ts-jest', otherwise it won't work.

Adding '^.+\\.js$': 'babel-jest' was not enough for me. Tests run only on empty cache once and started throwing Unexpected token errors on change. As mentioned here I also had to add transformIgnorePatterns ['<rootDir>/node_modules/'] to my jest.config.js
Full jest.config.js
module.exports = {
  moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
    '^.+\\.(js|jsx)?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: ['jest-serializer-vue'],
  testMatch: [
    '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
  ],
  transformIgnorePatterns: ['<rootDir>/node_modules/']
};

For now everything seems to be good now.

Same issue. None of the proposed solutions works for me

+1

Same issue about my tests.. Again none of the solutions worked for me..

+1

Is everyone here using windows? I didn't reproduce the error on mac.

Note: I can't reproduce on the dev environment.

Is everyone here using windows?
I'm using Ubuntu 18.04

npm i -D jest babel-jest babel-preset-es2015 babel-preset-react react-test-renderer

I did a full clean as proposed by @joebartels above, and updated (through the UI) to RC3, but to no avail. Same errors.
It seems to appears only in my tests involving vuex.

I’m running on Mac. I configured this for vuejs. And it worked for me.

I can't reproduce the issue on Windows 10 & Node 10.4.1:

with the cloned version
after upgrading the dependencies: see https://github.com/ijdickinson/vue-cli-jest-problem/pull/1 (needed to change the jest config for Windows following a fix in the jest generator which will be available in the next release).

For anyone that this may be able to help, I ran into this issue because my IDE auto-imported a library the wrong way: import { put, ... } from 'redux-saga/es/effects'; vs import { put, ... } from 'redux-saga';

That's it ? Closed ? Well, I am on a Mac, with RC3, and still have the exact same errors. I tried everything that is suggested in this thread. For the archive, here is my latest jest.config.js:
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.js$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
  ],
  transformIgnorePatterns: ['<rootDir>/node_modules/']
}

Since it was failing on my newly created test file, I decided to remove it. But after 2 min, not happy with this situation, I wanted to retry. And all green ! Tested again, all green.
There must be something fishy with a cache somewhere, no?

@onekiloparsec that loosely resembles what happened to me.
However, instead of removing the file and placing it back, I started a new project with latest vue-cli  (@vue/vue-cli (rc.3)) and one-by-one copied files from the "broken" directory into the new one...

I had a similar problem importing a plain JS vuejs-datepicker locale file, adding the following two fields in my jest config helped:
"transform": {
  "^.+\\.js$": "babel-jest",
  ...
},
"transformIgnorePatterns": ["node_modules/(?!(vuejs-datepicker/dist)/)"],
...

I also ran jest --clearCache afterwards, and naturally added babel-jest to my dependencies.

i have the same problem. when i change the jest.config.js like below, is worked.
it seem that we nedd trasform vue frist ,then transform js.
transform: {
'^.+\.vue$': 'vue-jest',
'^.+\.js$': 'babel-jest'
},

vue create foobar

Added Unit tests
Selected Jest

npm test:unit
Fails: SyntaxError: Unexpected token import
Windows 10

Steps
vue create foobar

Added Unit tests
Selected Jest
Dedicated config files
Using yarn

cd foobar
npm run test:unit
PASS  tests/unit/HelloWorld.spec.js
  HelloWorld.vue
    ✓ renders props.msg when passed (37ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.91s
Ran all test suites.

System
macOS 10.14 Beta
Vue-Cli 3.0.0

+1

Speaking w.r.t. an existing project. I had the same issue. I resolved it by following the steps done by Vue-CLI (3.0) scaffolding for new projects.
deps added:
    "@vue/cli-plugin-unit-jest": "^3.0.1",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.0.1",

scripts added:
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e",

jest.config.js
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testURL: 'http://localhost/'
}

No specific changes to babel configuration.

I have the exact same issue after it has been working the entire time. Even the suggested solution doesn't fix it for me, I also haven't changed anything besides updating to latest vue-cli dependencies.

I had a quick encounter with this as well, but for me it was something different:
I was using lodash-es, which uses ES6 modules - and since jest won't transform anything from /node_modules by default, this meant I was getting code with import and export statements into my tests, which of course broke.
When I added the following to my jest config, it worked:
transformIgnorePatterns: [
  '<rootDir>/node_modules/(?!lodash-es)'
],

It is happening in a fresh project. Error is in .spec.js file.

I haven't been able to resolve this issue, but there seems to be a discussion in the Jest repository which seems related.

@znvk funnily enough, after I messed with a bunch of package versions in my current small project and resorted to wipe yarn.lock and reinstall everything, my tests now break as well. :/

I "fixed" this problem for my project by adding the .vue extension to the imports in tests. Hope this helps.
-import Component from './Component';
+import Component from './Component.vue';

Hi all, after attempting all the above solution such as transform, clear cache etc and still could not get it to work, I restarted my laptop and magically everything work now. At least for me it obviously has something to do with caching. If you have came across the same issue, restart now might help you save 2 precious hours.

I was unable to resolve the issue with all the solutions offered here, and ended up just moving the project folder to a temporary location. This fixed the issue for me. So my guess is also related to caching.

Seems to be a problem with babel integration in Jest. After trying all suggestions in this thread without success I read this Jest doc page and finally I solved it.
I did the next changes in my config files:
package.json:
+"@babel/core": "*",
+"@babel/preset-env": "*",
+"babel-core": "7.0.0-bridge.0",
+"babel-jest": "*",

babel.config.js:
module.exports = {
  presets: [
+  '@babel/preset-env',
    @vue/app',
  ],
};

Before the changes I execute these commands in order to start the installation of dependencies as clean as possible, not sure if they are needed:
rm -rf node_modules && rm -rf ~/.npm/ && npm cache clean --force && npm install
Thanks to @mmtr for the clue of babel. Hope this solution works for all of you.

Hm that would be weird. All of these dependencies are already installed directly or indirectly, and @vue/preset-app includes @babel/preset-app, so adding that shouldn't make a difference either.

Hi Linus, thanks for your response.
I can reproduce the problem moving the babel-jest dependency to the 23.4.2 version, you are right, I don't need to define the babel preset and the @babel dependencies explicitly.
If I move the babel-jest to the 23.6.0 version, the problem is solved and all test goes green.
So this reduce the solution to:
-"babel-jest": "23.4.2",
+"babel-jest": "23.6.0",

I'm removing the package-lock.json before installing the dependencies, remove .npm folder or clean the cache seems to have no effect.

i have the same problem. when i change the jest.config.js like below, is worked.
it seem that we nedd trasform vue frist ,then transform js.
transform: {
'^.+.vue$': 'vue-jest',
'^.+.js$': 'babel-jest'
},

Thanks, that solved my problem! :+1: :+1: I never guessed it.

I have tried all variations of the above solutions, on ubuntu 18.04, none work. I cleared cache after every attempt, and have restarted my computer several times.
package.json
    "transform": {
      "^.+\\.vue$": "vue-jest",
      "^.+\\.js$": "babel-jest",
      "^.+\\.jsx?$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
    },

example.spec.js
import { shallowMount } from '@vue/test-utils'
import HelloWorld from<EMAIL_ADDRESS>
describe('HelloWorld.vue', () => {
    it('renders props.msg when passed', () => {
        const msg = 'new message'
        const wrapper = shallowMount(HelloWorld, {
            propsData: { msg }
        })
        expect(wrapper.text()).toMatch(msg)
    })
})

Error:

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

@komali2 Have you tried checking out the repository in a new location?

Also having the same issue with a newly created project. I also believe it is some caching issue, because it work once sometime after changes.
module.exports = {
  moduleFileExtensions: ["vue", "js", "jsx", "json", "ts", "tsx"],
  transform: {
    "^.+\\.vue$": "vue-jest",
    "^.+\\.tsx?$": "ts-jest",
    "^.+.js$": "babel-jest",
    ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$":
      "jest-transform-stub"
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  snapshotSerializers: ["jest-serializer-vue"],
  testMatch: [
    "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
  ],
  testURL: "http://localhost/"
};

Babel config name : babel.config.js
Jest Config name: jest.config.js
Test file under tests/unit/*.spec.ts

@komali2 Have you tried checking out the repository in a new location?

Can you clarify what you mean? Do you mean do a full project tear down? Not yet, I can try if necessary. I have wiped out node_modules, that should take care of caching, is that what you suspect?

@komali2 Sure, I meant doing a fresh git clone of the repository in a different location, e.g. a parent folder. In my case this was the only solution, I suspect it is related to some caching issue.

@morkro That didn't work. The babel-jest people are saying something about converting a .babelrc to a .babel.config.js, but as I use vue-cli, I don't have a .babelrc.

@komali2 Have you tried to delete the node_modules folder?
You can delete the folder running on your terminal rm -rf node_modules

@marlonbarcarol  Yes, I've done this.

I'm a bit out of things to recommend. Just to make sure: I are running vue-cli-service test: unit command, not jest directly, right?

@LinusBorg  Cheers, correct. Here's the whole package.json:
{
"name": "example",
"version": "1.0.0",
"private": true,
"description": "example",
"main": "build/index.js",
"scripts": {
"build": "npm run build:ui && npm run build:api",
"build:api": "tsc && rsync -a --include '/' --include '.txt' --exclude '' lib/ build/",
"lint": "tslint 'lib/**/.ts' && eslint --ext .js,.vue client/src",
"lint:api": "tslint lib//.ts",
"pretest": "find build -name '.integration.' -delete && ./scripts/check_nodejs_version.sh && tsc",
"start": "node build/index.js",
"test": "NODE_ENV=test nyc mocha",
"serve:ui": "vue-cli-service serve client/src/main.js",
"build:ui": "vue-cli-service build --dest build/public/ client/src/main.js",
"lint:ui": "vue-cli-service lint",
"test:unit:ui": "vue-cli-service test:unit"
},
"dependencies": {
"@types/bcrypt": "^1.0.0",
"@types/bunyan": "^1.8.4",
"@types/config": "0.0.33",
"@types/handlebars": "^4.0.38",
"@types/ioredis": "^3.2.11",
"@types/koa": "^2.0.46",
"@types/koa-bodyparser": "^3.0.20",
"@types/koa-router": "^7.0.30",
"@types/koa-send": "^4.1.0",
"@types/node": "^8.10.25",
"@types/nodemailer": "^4.6.2",
"aws-sdk": "^2.268.1",
"axios": "^0.17.1",
"bcrypt": "^1.0.3",
"bluebird": "^3.5.1",
"bull": "^3.4.7",
"bunyan": "^1.8.12",
"bunyan-syslog"<EMAIL_ADDRESS>"config": "^1.30.0",
"d3": "^4.12.0",
"font-awesome-webpack": "^0.0.5-beta.2",
"handlebars": "^4.0.11",
"ioredis": "^3.2.2",
"jquery": "^3.2.1",
"koa": "^2.0.0",
"koa-bodyparser": "^3.1.0",
"koa-router": "^7.0.1",
"koa-send": "^4.1.2",
"materialize-css": "^0.100.2",
"md5": "^2.2.1",
"mjml": "^4.1.0",
"moment": "^2.22.2",
"nodemailer": "^4.6.7",
"otplib": "^10.0.1",
"pg-promise": "^7.3.1",
"vue": "^2.5.12",
"vue-resource": "^1.3.5",
"vue-router": "^3.0.1",
"vue2-ace-editor": "0.0.3",
"webpack": "^4.20.2"
},
"devDependencies": {
"@types/bluebird": "^3.5.21",
"@types/bull": "^3.3.19",
"@types/chai": "^4.1.4",
"@types/mjml": "^4.0.0",
"@types/mocha": "^2.2.33",
"@types/uuid": "^3.4.3",
"@vue/cli-plugin-babel": "^3.0.4",
"@vue/cli-plugin-eslint": "^3.0.4",
"@vue/cli-plugin-unit-jest": "^3.0.4",
"@vue/cli-service": "^3.0.4",
"@vue/eslint-config-standard": "^3.0.4",
"@vue/test-utils": "^1.0.0-beta.20",
"autoprefixer": "^7.2.3",
"babel-eslint": "^8.2.5",
"babel-jest": "^23.6.0",
"babel-loader": "^7.1.5",
"babel-plugin-istanbul": "^4.1.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-2": "^6.24.1",
"babel-register": "^6.26.0",
"chai": "^4.2.0",
"cross-env": "^5.2.0",
"cross-spawn": "^5.1.0",
"css-loader": "^0.28.7",
"eslint": "^4.13.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-html": "^4.0.5",
"inject-loader": "^3.0.1",
"karma": "^3.0.0",
"karma-coverage": "^1.1.1",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-phantomjs-shim": "^1.4.0",
"karma-sinon-chai": "^1.3.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.31",
"karma-webpack": "^2.0.2",
"madge": "^3.2.0",
"mocha": "^4.0.1",
"mocha-typescript": "^1.1.16",
"nightwatch": "^1.0.6",
"node-notifier": "^5.1.2",
"nyc": "^13.0.0",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"phantomjs-prebuilt": "^2.1.14",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.9",
"rimraf": "^2.6.2",
"selenium-server": "^3.13.0",
"semver": "^5.4.1",
"shelljs": "^0.7.8",
"sinon": "^4.0.0",
"sinon-chai": "^2.8.0",
"source-map-support": "",
"ts-node": "^3.3.0",
"tslint": "^5.10.0",
"typescript": "^2.9.2",
"uglifyjs-webpack-plugin": "^1.2.7",
"uuid": "^3.3.2",
"vue-loader": "^15.4.2",
"vue-style-loader": "^3.0.3",
"vue-template-compiler": "^2.5.12",
"webpack-bundle-analyzer": "^2.13.1",
"webpack-dev-server": "^3.1.9",
"webpack-merge": "^4.1.3"
},
"nyc": {
"check-coverage": true,
"lines": 0,
"statements": 0,
"functions": 0,
"branches": 0,
"include": [
"build/api//.js"
],
"exclude": [
"test/**/.js"
],
"reporter": [
"lcov",
"text-summary"
],
"all": true
},
"engines": {
"node": ">= 8.11.0",
"npm": ">= 5.6.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"jest": {
"moduleFileExtensions": [
"js",
"jsx",
"json",
"vue"
],
"transform": {
"^.+\.vue$": "vue-jest",
"^.+\.js$": "babel-jest",
"^.+\.jsx?$": "babel-jest",
".+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
"moduleNameMapper": {
"^@/(.)$": "/src/$1"
},
"snapshotSerializers": [
"jest-serializer-vue"
],
"testMatch": [
"/tests/unit//.spec.(js|jsx|ts|tsx)|**/tests/*.(js|jsx|ts|tsx)"
],
"testURL": "http://localhost/"
}
}

And the Babel config?

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

thanks for sticking with me :)

Looking fine as well :-/
Last straw: do you have any suspicious env variables set on it system? Check printenv, e.g. for NODE_ENV or any VUE_CLI_* variables

Nope :(

I should note, it's not working on any machine in this office...

I was getting the same error message, I fixed this by adding to my package.json:
`

"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"babel": {
"presets": [

 "@babel/preset-env",

 [

   "@vue/app",

   {

     "useBuiltIns": "entry"

   }

 ]

]
},
`

Also, I've removed the babel.config.js file.
Hope this helps to find the root cause.

@msurdi our babel-preset wraps preset-env, so adding it should have no effect. If it has, then its ab out an option that we can set on our preset as well.

@msurdi this causes the following error:
  ● Test suite failed to run

    Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel. (While processing preset<EMAIL_ADDRESS>
      at throwVersionError (node_modules/@babel/preset-env/node_modules/@babel/helper-plugin-utils/lib/index.js:65:11)
      at Object.assertVersion (node_modules/@babel/preset-env/node_modules/@babel/helper-plugin-utils/lib/index.js:13:11)
      at _default (node_modules/@babel/preset-env/lib/index.js:154:7)
      at node_modules/@babel/preset-env/node_modules/@babel/helper-plugin-utils/lib/index.js:19:12
      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:317:46
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

package.json
{
  "name": "example",
  "version": "1.0.0",
  "private": true,
  "description": "example",
  "main": "build/index.js",
  "scripts": {
    "build": "npm run build:ui && npm run build:api",
    "build:api": "tsc && rsync -a --include '*/' --include '*.txt' --exclude '*' lib/ build/",
    "lint": "tslint 'lib/**/*.ts' && eslint --ext .js,.vue client/src",
    "lint:api": "tslint lib/**/*.ts",
    "pretest": "find build -name '*.integration.*' -delete && ./scripts/check_nodejs_version.sh && tsc",
    "start": "node build/index.js",
    "test": "NODE_ENV=test nyc mocha",
    "serve:ui": "vue-cli-service serve client/src/main.js",
    "build:ui": "vue-cli-service build --dest build/public/ client/src/main.js",
    "lint:ui": "vue-cli-service lint",
    "test:unit:ui": "vue-cli-service test:unit"
  },
  "dependencies": {
    "@types/bcrypt": "^1.0.0",
    "@types/bunyan": "^1.8.4",
    "@types/config": "0.0.33",
    "@types/handlebars": "^4.0.38",
    "@types/ioredis": "^3.2.11",
    "@types/koa": "^2.0.46",
    "@types/koa-bodyparser": "^3.0.20",
    "@types/koa-router": "^7.0.30",
    "@types/koa-send": "^4.1.0",
    "@types/node": "^8.10.25",
    "@types/nodemailer": "^4.6.2",
    "aws-sdk": "^2.268.1",
    "axios": "^0.17.1",
    "bcrypt": "^1.0.3",
    "bluebird": "^3.5.1",
    "bull": "^3.4.7",
    "bunyan": "^1.8.12",
    "bunyan-syslog"<EMAIL_ADDRESS>    "config": "^1.30.0",
    "d3": "^4.12.0",
    "font-awesome-webpack": "^0.0.5-beta.2",
    "handlebars": "^4.0.11",
    "ioredis": "^3.2.2",
    "jquery": "^3.2.1",
    "koa": "^2.0.0",
    "koa-bodyparser": "^3.1.0",
    "koa-router": "^7.0.1",
    "koa-send": "^4.1.2",
    "materialize-css": "^0.100.2",
    "md5": "^2.2.1",
    "mjml": "^4.1.0",
    "moment": "^2.22.2",
    "nodemailer": "^4.6.7",
    "otplib": "^10.0.1",
    "pg-promise": "^7.3.1",
    "vue": "^2.5.12",
    "vue-resource": "^1.3.5",
    "vue-router": "^3.0.1",
    "vue2-ace-editor": "0.0.3",
    "webpack": "^4.20.2"
  },
  "devDependencies": {
    "@babel/core": "^7.1.2",
    "@babel/preset-env": "^7.1.0",
    "@types/bluebird": "^3.5.21",
    "@types/bull": "^3.3.19",
    "@types/chai": "^4.1.4",
    "@types/mjml": "^4.0.0",
    "@types/mocha": "^2.2.33",
    "@types/uuid": "^3.4.3",
    "@vue/cli-plugin-babel": "^3.0.4",
    "@vue/cli-plugin-eslint": "^3.0.4",
    "@vue/cli-plugin-unit-jest": "^3.0.4",
    "@vue/cli-service": "^3.0.4",
    "@vue/eslint-config-standard": "^3.0.4",
    "@vue/test-utils": "^1.0.0-beta.20",
    "autoprefixer": "^7.2.3",
    "babel-eslint": "^8.2.5",
    "babel-jest": "^23.6.0",
    "babel-loader": "^7.1.5",
    "babel-plugin-istanbul": "^4.1.5",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-register": "^6.26.0",
    "chai": "^4.2.0",
    "cross-env": "^5.2.0",
    "cross-spawn": "^5.1.0",
    "css-loader": "^0.28.7",
    "eslint": "^4.13.1",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-html": "^4.0.5",
    "inject-loader": "^3.0.1",
    "karma": "^3.0.0",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.3.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-phantomjs-shim": "^1.4.0",
    "karma-sinon-chai": "^1.3.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.31",
    "karma-webpack": "^2.0.2",
    "madge": "^3.2.0",
    "mocha": "^4.0.1",
    "mocha-typescript": "^1.1.16",
    "nightwatch": "^1.0.6",
    "node-notifier": "^5.1.2",
    "nyc": "^13.0.0",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "ora": "^1.2.0",
    "phantomjs-prebuilt": "^2.1.14",
    "portfinder": "^1.0.13",
    "postcss-import": "^11.0.0",
    "postcss-loader": "^2.0.9",
    "rimraf": "^2.6.2",
    "selenium-server": "^3.13.0",
    "semver": "^5.4.1",
    "shelljs": "^0.7.8",
    "sinon": "^4.0.0",
    "sinon-chai": "^2.8.0",
    "source-map-support": "*",
    "ts-node": "^3.3.0",
    "tslint": "^5.10.0",
    "typescript": "^2.9.2",
    "uglifyjs-webpack-plugin": "^1.2.7",
    "uuid": "^3.3.2",
    "vue-loader": "^15.4.2",
    "vue-style-loader": "^3.0.3",
    "vue-template-compiler": "^2.5.12",
    "webpack-bundle-analyzer": "^2.13.1",
    "webpack-dev-server": "^3.1.9",
    "webpack-merge": "^4.1.3"
  },
  "nyc": {
    "check-coverage": true,
    "lines": 0,
    "statements": 0,
    "functions": 0,
    "branches": 0,
    "include": [
      "build/api/**/*.js"
    ],
    "exclude": [
      "test/**/*.js"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ],
    "all": true
  },
  "engines": {
    "node": ">= 8.11.0",
    "npm": ">= 5.6.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "vue"
    ],
    "transform": {
      "^.+\\.vue$": "vue-jest",
      "^.+\\.js$": "babel-jest",
      "^.+\\.jsx?$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
    },
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/src/$1"
    },
    "snapshotSerializers": [
      "jest-serializer-vue"
    ],
    "testMatch": [
      "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
    ],
    "testURL": "http://localhost/"
  },
  "babel": {
    "presets": [
      "@babel/preset-env",
      [
        "@vue/app",
        {
          "useBuiltIns": "entry"
        }
      ]
    ]
  }
}

I wiped the node_modules and npm cache before attempting.

preset-env

What does that mean? How that relate to Vuejs problem we are having?

Please see how to clear jest cache.

@Akryum I can confirm this is still an issue. I cleared the Jest cache like you said and I am still getting the "SyntaxError: Unexpected token import" error.
I am on Windows 10.

Alright, Windows was not the issue.  I was able to get Jest running with Vue CLI 3 again with the steps below:
Create .env.test in your project root.
Add these two variables to the file:
VUE_CLI_BABEL_TARGET_NODE=true
VUE_CLI_BABEL_TRANSPILE_MODULES=true

Save and run Jest from the CLI GUI and it should work.

I tried all of the above, but it not work
environment
mac:10.13.6
node: v8.12.0
npm: 6.4.1
vue: 3.0.5

I'm experiencing this as well.
Linux 16.04
Node 10.x
vue-cli 3.x
Tried everything, no luck :( I just want to write tests

I must say I am a bit puzzled by the duration of that issue, and the absence of even a hint on the solution we could build to solve it.

the only way I resolved it is by NOT to use vue-cli but use its babel plugin.. (ironically). whoever'd like to temporarily unjam themselve, feel free to take a look! https://github.com/adamchenwei/vuejs-storybook-storyshot-jest-webpack-boilerplate

Please see how to clear jest cache.

I ran node node_modules/jest/bin/jest.js --clearCache
Did not work.
So, I did it again, then rm -rf node_modules, cleared npm cache, npm installed, then ran the jest cache clear again, then tried testing again, did not work.

VUE_CLI_BABEL_TARGET_NODE=true VUE_CLI_BABEL_TRANSPILE_MODULES=true

I did
.env.test
VUE_CLI_BABEL_TARGET_NODE=true
VUE_CLI_BABEL_TRANSPILE_MODULES=true

This did not solve the issue.

For what it's worth, in my case this problem is caused by ts-jest, since version 23.10.3. Version 23.10.2 works correctly.
Edit: fixed it by replacing the contents of my jest.config.js with
module.exports = {
  preset: 'ts-jest'
}

Versions:
"@types/jest": "^23.3.9",
"jest": "^23.6.0",
"ts-jest": "^23.10.4",

"plugin ts-jest not found"
Solution did not work

@komali2 its something wrong with babel and NODE_ENV

I've solved the issue.
Make sure you have these exact versions of the following packages installed:
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.0.5",
    "@vue/cli-plugin-eslint": "^3.0.5",
    "@vue/cli-plugin-unit-jest": "^3.0.5",
    "@vue/cli-service": "^3.0.5",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.0.1",
    "vue-template-compiler": "^2.5.17"
  },

  "dependencies": {
    "vue": "^2.5.17"
  },

Only with this exact combination were we able to get jest tests to work.

@jewbetcha  what's confusing? What more information can I give you? What error are you getting with the above?

It's works for me with this line:
'^.+\\.(js|jsx)?$': '<rootDir>/node_modules/babel-jest'

Any idea why jest does not find babel-jest?

@komali2 nothing confusing, it's just tough to jump around versions with a pre-existing project. I'm not sure I'll be able to try that solution or not

@jewbetcha why won't you be able to try it? Just try it lol

None of these solutions worked for me.. getting the same issue

I've solved the issue, looks like a bug with babel.config.js.
Try this:

Delete babel.config.js

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

Create .babelrc

{
  "presets": [
    ["env", { "modules": false }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", { "targets": { "node": "current" }}]
      ]
    }
  }
}

npm i --save-dev babel-preset-env

same here, tried everything, still won't work

I have encountered the same problem.
After trying all the solutions above, I tried to update all the package to the latest version.  And then for some search results that I execute 'yarn', in reason unknown that I have solved the problem.
It would be great if anyone can tell me the reason.
This part added in package.json
 "babel": {     "presets": [       "@babel/preset-env",       [         "@vue/app",         {           "useBuiltIns": "entry"         }       ]     ]   },
The other parts are the same as of what vue-cli provided by default.

I tried many of the above solutions. In the end, running jest --clearCache finally solved the problem for me. So the actual fix could have been any combination of the above solutions. The problem was I thought that running rm -rf node_modules and npm install, which I also tried many times, would effectively clear the cache, but apparently it didn't.

Wow, this has been going on.. is there still no stable solution?

Thanks @LinusBorg for letting us know you're still aware of the issue.
I am not 100% sure that adding one more thing is useful, but I just tried and succeeded to workaround the problem on my side, after having tried everything that is proposed in this thread. I tend to think the  workaround indicates there are different problems involved in this thread, and thus should be closed, while new issues must be reopened for each individual problem.
So, here it is. The error message I had is exactly what has been invoked in the first place, that is an SyntaxError: Unexpected token import. Here is the message (it comes from a test of a Login component, with 2 input fields and a login button).
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/onekiloparsec/code/arcsecond-front/node_modules/vue-skycons/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Skycons from './skycons';
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

      28 |
      29 | import LabelCentered from '@/components/labels/LabelCentered'
    > 30 | import LabelError from '@/components/labels/LabelError'
         |                                          ^
      31 |
      32 | import skyUtils from './mixins/skyUtils'
      33 | import dateUtils from './mixins/dateUtils'

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/main.js:30:42)
      at Object.<anonymous> (src/store/modules/auth.js:18:13)

Two things I note here: 1) the failing import has nothing to do with the test itself, and 2) the error "cursor" (at line 30) seems unrelated to the error itself too. So very strange. If I comment the import of Skycons, it fails the same way on another similar import line.
At that point, I noticed that importing Skycons is totally silly for running my tests. My feeling was that my tests setup was importing way too many and unnecessary things.
There were 2 difficulties in my tests: mixins and a Vuex store. In particular, the Vuex store was importing one of the actualy vuex module/namespace: auth (see the last line of error message).
I worked around the test error by stubbing entirely the auth vuex module.
Here is my test (LabelError is a custom component used to display an error message): Login.spec.js:
import Vuex from 'vuex'
import { createLocalVue, RouterLinkStub, shallowMount } from '@vue/test-utils'

import assetsSourcePaths from '@/mixins/assetsSourcePaths'
import Login from<EMAIL_ADDRESS>
const localVue = createLocalVue()
localVue.use(Vuex)

describe('Login.vue', () => {
  let auth = { namespaced: true }
  let store
  let wrapper

  beforeEach(() => {
    auth.actions = {
      loginUser: jest.fn()
    }

    store = new Vuex.Store({
      modules: {
        auth
      },
      strict: true
    })

    wrapper = shallowMount(Login, {
      localVue,
      store,
      stubs: {
        RouterLink: RouterLinkStub,
        LabelError: true
      },
      mixins: [
        assetsSourcePaths
      ]
    })
  })

  it('has a title', () => {
    expect(wrapper.find('h2').text()).toMatch('Log In')
  })

  it('has valid default data', () => {
    expect(wrapper.vm.isLoggingIn).toBe(false)
    expect(wrapper.vm.loginError).toBe(null)
  })

  it('has two inputs', () => {
    const inputArray = wrapper.findAll('input')

    expect(inputArray.at(0).element.value).toMatch('')
    expect(inputArray.at(1).element.value).toMatch('')

    expect(inputArray.at(0).attributes().name).toMatch('username')
    expect(inputArray.at(1).attributes().name).toMatch('password')

    expect(inputArray.at(0).attributes().type).toMatch('text')
    expect(inputArray.at(1).attributes().type).toMatch('password')

    expect(inputArray.at(0).attributes().disabled).toBeUndefined()
    expect(inputArray.at(1).attributes().disabled).toBeUndefined()

    expect(inputArray.at(0).contains('p.text-danger')).toBe(false)
    expect(inputArray.at(1).contains('p.text-danger')).toBe(false)
  })

  it('has a button', () => {
    expect(wrapper.contains('button')).toBe(true)
    expect(wrapper.find('button').attributes().name).toBe('submit')
    expect(wrapper.find('button').attributes().disabled).toBeDefined()
  })

  it('should trigger login when button is clicked', (done) => {
    const credentials = { username: 'john', password: 'doe' }
    wrapper.setData({ credentials: credentials })

    const button = wrapper.find('button')
    button.trigger('click')
    expect(auth.actions.loginUser).toHaveBeenCalled()
    expect(auth.actions.loginUser.mock.calls[0][1]).toEqual(credentials)

    expect(button.attributes().disabled).toBeDefined()

    expect(wrapper.vm.isLoggingIn).toBe(true)
    expect(wrapper.vm.loginError).toBe(null)

    const inputArray = wrapper.findAll('input')
    expect(inputArray.at(0).attributes().disabled).toBeDefined()
    expect(inputArray.at(1).attributes().disabled).toBeDefined()

    wrapper.vm.$nextTick(() => {
      expect(wrapper.vm.isLoggingIn).toBe(false)
      expect(wrapper.vm.loginError).toBe(null)
      done()
    })
  })
})

And here are my configs: babel.config.js:
module.exports = {
  presets: [
    '@vue/app'
  ]
}

And jest.config.js:
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  transformIgnorePatterns: [
    '<rootDir>/node_modules/',
    '<rootDir>/dist/'
  ],
  testURL: 'http://localhost/',
  setupFiles: [
    'jest-localstorage-mock'
  ]
}

Vue version: 3.0.5 (I started to note the problems since -RC3).

This issue drives me crazy.
I can get a vue-cli based project working now, by copying it to another drive on my win10 machine.
So, the original is on the d drive. When I copy the sources (except node_modules folder) to the E drive, do there an npm install, all tests work just fine.
On the other hand, when I delete in the source folder on the d drive, the node_modules folder, do an npm install, the tests still fail.
One would expect that after a delete of npm folder on drive d, the situation on both d and f drive are the same, but it's not :(

Also having this issue ;/
https://stackoverflow.com/questions/53397773/node-modules-not-being-parsed-correctly-for-tests

I was having this issue too. This is how I got the tests working again.
I had to install the version 7.0.0-bridge.0 for babel-core.
"babel-core": "7.0.0-bridge.0"
There is a message in the bable-jest repo about this.

Note: If you are using babel version 7 you have to install babel-jest with
yarn add --dev babel-jest<EMAIL_ADDRESS>@babel/core

and the Vue cli-plugin-babel is installing @bable/core ^7.0.0
I hope this helps anyone still having this issue.

Interesting. The lastest version of the vue cli is actually already setup to include this dependency, here's what I'm seeing in my package.json:
"babel-core": "7.0.0-bridge.0",

Obviously for me, just having that didn't solve me problem. Only this did it for me:
https://github.com/vuejs/vue-cli/issues/1584#issuecomment-439718686

@LinusBorg If you need an additional repo for reproducing:
https://github.com/paulvanbladel/quasar-jest/tree/master/quasar-with-vue-cli
It's a quasar app, but generated with the vue-cli 3.
Cheers.

Thanks.

I encountered a weird side effect: Running all tests (npm run test:unit) works without problems, running one specific test (npm run test:unit -t App for App.spec.js) fails.
The script: "test:unit": "vue-cli-service test:unit --no-cache"
    Details:

    SyntaxError: [BABEL] unknown: Unexpected token m in JSON at position 0 (While processing<EMAIL_ADDRESS>        at JSON.parse (<anonymous>)

      at Object.parseSourceMapInput (node_modules/jest-runner/node_modules/source-map/lib/util.js:433:15)
          at Array.map (<anonymous>)
      at extendedTrace (node_modules/@babel/template/lib/builder.js:70:15)
      at Object.assign.args (node_modules/@babel/template/lib/builder.js:27:14)
      at exports.default (node_modules/babel-plugin-dynamic-import-node/lib/index.js:13:21)
      at loadDescriptor (node_modules/@babel/core/lib/config/full.js:165:14)
      at cachedFunction (node_modules/@babel/core/lib/config/caching.js:33:19)
      at loadPluginDescriptor (node_modules/@babel/core/lib/config/full.js:200:28)
      at config.plugins.reduce (node_modules/@babel/core/lib/config/full.js:69:20)
          at Array.reduce (<anonymous>)

package.json

  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.1.1",
    "@vue/cli-plugin-unit-jest": "^3.1.1",
    "@vue/cli-service": "^3.1.4",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.0.1",
    ...
  }

babel.config.js

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

jest.config.js

module.exports = {
  moduleFileExtensions: ["js", "jsx", "json", "vue"],
  verbose: true,
  transform: {
    "^.+\\.vue$": "vue-jest",
    ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$":
      "jest-transform-stub",
    "^.+\\.jsx?$": "babel-jest",
    "^.+\\.js$": "babel-jest"
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "^tests/(.*)$": "<rootDir>/tests/$1"
  },
  snapshotSerializers: ["jest-serializer-vue"],
  testMatch: [
    "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
  ],
  testURL: "http://localhost/"
};

if anyone trying to use the nuxt.js/examples/jest-vtu-example/ is having this issue, mine  was failing on the transform config.
in nuxt.js/examples/jest-vtu-example/ the package.json has
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
Adding parentheses around the file extension solved it for me
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
complete package.json
{
  "name": "bizziapp",
  "version": "0.9.0",
  "description": "The best CRM we know.",
  "author": "Temify",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "test": "jest ."
  },
  "dependencies": {
    "nuxt": "latest",
    "@nuxtjs/auth": "^4.5.3",
    "@nuxtjs/axios": "^5.3.6",
    "cross-env": "^5.2.0",
    "element-theme-chalk": "^2.4.9",
    "element-ui": "^2.4.6",
    "normalize.css": "^8.0.1",
    "nuxt-i18n": "^5.4.4"
  },
  "devDependencies": {
    "@babel/core": "^7.1.6",
    "@vue/test-utils": "^1.0.0-beta.25",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^23.6.0",
    "element-theme": "^2.0.1",
    "eslint": "^5.9.0",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-vue": "^4.0.0",
    "jest": "^23.6.0",
    "jest-puppeteer": "^3.5.1",
    "jest-serializer-vue": "^2.0.2",
    "node-sass": "^4.10.0",
    "nodemon": "^1.18.6",
    "nuxt-sass-resources-loader": "^2.0.5",
    "puppeteer": "^1.10.0",
    "sass-loader": "^7.1.0",
    "vue-jest": "^3.0.0"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "vue"
    ],
    "watchman": false,
    "moduleNameMapper": {
      "^~/(.*)$": "<rootDir>/$1",
      "^~~/(.*)$": "<rootDir>/$1"
    },
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
    },
    "snapshotSerializers": [
      "<rootDir>/node_modules/jest-serializer-vue"
    ],
    "collectCoverage": true,
    "collectCoverageFrom": [
      "<rootDir>/components/**/*.vue",
      "<rootDir>/pages/*.vue"
    ]
  }
}

@mvrska thx, but on https://github.com/paulvanbladel/quasar-jest/tree/master/quasar-with-vue-cli, it has not effect :(

Check your babel-core version.
I fix it by declare babel-core version to ^7.0.0-0" in package.json.
If not, installing babel-jest also brings you babel-core in version 6.26.3.
"devDependencies": {
    "@vue/cli-plugin-babel": "^3.0.1",
    "@vue/cli-plugin-eslint": "^3.0.1",
    "@vue/cli-service": "^3.0.1",
    "@vue/cli-plugin-unit-jest": "^3.0.1",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^23.6.0",
    "babel-core": "^7.0.0-0",
    "eslint": "^5.8.0",
    "eslint-plugin-vue": "^5.0.0-0",
    "jest": "^23.6.0",
    "vue-jest": "^3.0.0",
    "vue-template-compiler": "^2.5.17"
  }

@LinusBorg I updated https://github.com/paulvanbladel/quasar-jest/tree/master/quasar-with-vue-cli
to the latest vue bits. So please take that version also;
I appreciate the effort from everyone involved in this issue, but maybe we should verify the various proposed solutions against the same repo.
It is clear the the issue is based on something highly fragile (on bad days, I suspect the whole modern web dev world is highly fragile :) )
So, in order to exclude false positives, please test your proposed solution against the aforementioned repo, so that we can come up with something reproducable.
Thanks a lot !

@ijdickinson  It seem like a usual mistake when you set your bable.config.js  with below config:
 presets: [
    ['@babel/preset-env', { modules: false }]
]

you can not set modules: false when NODE_ENV is test, it make the babel not to transform the import syntax to commonjs, you can modify the babel.config like below to fix it:
const isDev = process.env.NODE_ENV === 'development'
 presets: [
    ['@babel/preset-env', { modules: isDev ? false : 'cjs' }]
]

OR
presets: [
   ['@babel/preset-env', { modules: false }]
],
// ... some other configuration
env: {
   test: {
      presets: [
           ['@babel/preset-env', { modules: 'cjs' }]
      ]
  }
}

NOTE: DONOT export a function in babel.config.js, just export a Object, like this:

module.exports = {
   presets: [ ... ],
   plugins: [ ... ],
   env: {
      test: { ... }
   }
}

For those use the cli, the docs indicate that for jest tests, the modules setting is

auto set to 'commonjs' in Jest tests

https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/babel-preset-app
Are you saying that's the right way to do it?

@dancon
Thanks. I tried your solution on  https://github.com/paulvanbladel/quasar-jest/tree/master/quasar-with-vue-cli, but no effect :(
What I am missing here to get it working?
so, babel.config.js becomes:
module.exports = {

  env: {
    test: {
       presets: [
            ['@babel/preset-env', { modules: 'cjs' }]
       ]
   }
 },
  presets: [
    '@vue/app',

  ],
  plugins: [
    [

      "transform-imports",
      {
        "quasar": {
          "transform": "quasar-framework/dist/babel-transforms/imports.mat.js",
          "preventFullImport": false
        }
      }
    ]
  ],
  comments: false
}

I've tried all the possible combinations from above and from other resources. This is the configuration that worked for me
.babelrc:
{
"presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}
]
],
"env": {
"test": {
"presets": [["env", { "targets": { "node": "current" } }]]
}
}
}
package.json:
...
"jest": {
"moduleFileExtensions": [
"js",
"vue"
],
"moduleNameMapper": {
"^@/(.)$": "/src/$1"
},
"transform": {
"^.+\.jsx?$": "babel-jest",
"^.+\.js$": "/node_modules/babel-jest",
".\.(vue)$": "/node_modules/vue-jest"
},
"transformIgnorePatterns": [
"/node_modules/(?!vue-awesome)"
],
"snapshotSerializers": [
"/node_modules/jest-serializer-vue"
],
"moduleDirectories": [
"node_modules",
"src"
]
},
...

I have tried a lot of solutions from above and from other sources. This is the configuration that worked for me
.babelrc:
   "presets":[
      [
         "env",
         {
            "modules":false,
            "targets":{
               "browsers":[
                  "> 1%",
                  "last 2 versions",
                  "not ie <= 8"
               ]
            }
         }
      ]
   ],
   "env":{
      "test":{
         "presets":[
            [
               "env",
               {
                  "targets":{
                     "node":"current"
                  }
               }
            ]
         ]
      }
   }
}

package.json:
 "jest": {
    "moduleFileExtensions": [
      "js",
      "vue"
    ],
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/src/$1"
    },
    "transform": {
      "^.+\\.jsx?$": "babel-jest",
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!vue-awesome)"
    ],
    "snapshotSerializers": [
      "<rootDir>/node_modules/jest-serializer-vue"
    ],
    "moduleDirectories": [
      "node_modules",
      "src"
    ]
  }

@naveensenapathi .
Thanks for that. Your suggestions work fine on my test repo:
https://github.com/paulvanbladel/quasar-jest/tree/master/quasar-with-vue-cli,

Adding --no-cache in the command worked to me!
So, my package.json script looks like this:
"test:unit": "vue-cli-service test:unit --no-cache"

Following what @naveensenapathi did I found the minimum configuration change that worked for me (not using vue-cli, but still ran into this issue)
// ... in package.json
"jest": {
    "transform": {
      "^.+\\.jsx?$": "babel-jest",
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest"   // this one line made the difference
    }
}

Thank you @naveensenapathi!
Complete configuration
package.json
{
  "dependencies": {
    "@rails/webpacker": "3.5",
    "axios": "^0.18.0",
    "babel-cli": "^6.26.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-app": "^3.1.2",
    "prop-types": "^15.6.2",
    "react": "^16.6.3",
    "react-dom": "^16.6.3",
    "react-on-rails": "11.1.8",
    "react-redux": "^5.1.1",
    "redux": "^4.0.1",
    "redux-logger": "^3.0.6",
    "resolve-url-loader": "^3.0.0",
    "webpack-merge": "^4.1.4"
  },
  "scripts": {
    "test": "jest",
    "test:watch": "npm test -- --watch"
  },
  "jest": {
    "verbose": true,
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "moduleNameMapper": {
      "\\.(css)$": "identity-obj-proxy"
    },
    "roots": [
      "client/bundles"
    ],
    "transform": {
      "^.+\\.jsx?$": "babel-jest",
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
    }
  },
  "devDependencies": {
    "babel-jest": "^23.6.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^23.6.0",
    "webpack-dev-server": "^3.1.10"
  }
}

.babelrc
{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": "> 1%",
          "uglify": true
        },
        "useBuiltIns": true
      }
    ],
    "react"
  ],
  "plugins": [
    "syntax-dynamic-import",
    "transform-object-rest-spread",
    [
      "transform-class-properties",
      {
        "spec": true
      }
    ]
  ],
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

Just install<EMAIL_ADDRESS>because babel-jest not fully supports babel@7, as far as I know.

Have same issue... I think something wrong with .babelrc

Damn it. Half year and this is still open! :)

I think i undertstand.
I have same issue and rebuild all configs but it is not help. I spend 2 + days and finally i found solution.
In the component that I imported, there was an import from the main.js file, so I imported the EventBus directly from main.js.
The solution was to put this very EventBus into a separate eventBus.js file and import it from there! That helped!
Remove import EventBus  in main.js:
and add in single file eventBus.js
Its work fine for me after this.

The challenge with this issue, demonstrated by the number of people reporting different solutions for their problem, is that it's hard to replicate the problem, or even to say if its one problem or many. It's just hard to pin down what's an issue with our cli, what's an issue with jest and what's an issue with a 3rd party lib imported by the user, for eaxmple.
We already fixed a couple of related issues, and I'm having the (subjective) impression that reports about this issue became rarer, but we'Re keeping i open to keep an eye on it.

I am using nuxt starter pack, and adding babelrc and jest config did the trick for me.

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

....spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { mount } from '@vue/test-utils';
                                                                                ^

SyntaxError: Unexpected token {

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

.babelrc
{   "env": {     "test": {       "plugins": ["transform-es2015-modules-commonjs"]     }   } }
jest.config.js
module.exports = {   moduleFileExtensions: ['js', 'json', 'vue'],   transform: {     '^.+\\.vue$': 'vue-jest',     '^.+\\.js?$': '<rootDir>/node_modules/babel-jest'   },   transformIgnorePatterns: ['<rootDir>/node_modules/'],   testMatch: ['**/tests/unit/*.spec.(js|jsx|ts|tsx)'] }
installed vue-jest manually

This thread is not about nuxt.

The challenge with this issue, demonstrated by the number of people reporting different solutions for their problem, is that it's hard to replicate the problem, or even to say if its one problem or many. It's just hard to pin down what's an issue with our cli, what's an issue with jest and what's an issue with a 3rd party lib imported by the user, for eaxmple.
We already fixed a couple of related issues, and I'm having the (subjective) impression that reports about this issue became rarer, but we'Re keeping i open to keep an eye on it.

You are right, but the common problem is: import is not a known command.
I think this is related to this issue: https://github.com/facebook/jest/issues/4842

I can reproduce this on a fresh project if I update `babel-jest:
npx @vue/cli create rep-jest-fail
cd rep-jest-fail
npx @vue/cli add @vue/unit-jest
# ✓ Passes

# Update babel-jest to `^24.0.0` (is on `23.6.0` by default)
npm install --save-dev babel-jest@latest
npm run test:unit
# ✘ Fails

Output:
    /tmp/jest-fail/tests/unit/example.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '@vue/test-utils';
                                                                                ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Note that downgrading babel-jest will not fix the problem on my machine (I don't know why).

To workaround this problem in my project, I had to install jest manually instead of depending on @vue/cli-plugin-unit-jest:

uninstall @vue/cli-plugin-unit-jest;
install<EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS>install both<EMAIL_ADDRESS>and<EMAIL_ADDRESS>add these lines to the top of vue.config.js:

process.env.VUE_CLI_BABEL_TARGET_NODE = true;
process.env.VUE_CLI_BABEL_TRANSPILE_MODULES = true;

Once @vue/cli-plugin-unit-jest and vue-jest update to Babel 7, it should hopefully be possible to drop the dependency on babel-core and just install @vue/cli-plugin-unit-jest instead :)

No joy @candu  got this instead
    /Users/lee/Source/carbon/carbon-components-vue/tests/unit/cv-tag.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.array.iterator";

However, after installing those directly, and then adding @vue/cli-plugin-unit-jest back I was able to get it to work.
Only downside is my Storybook build fails due to babel-core :-(
So I changed my unit test script to....
"test:unit": "yarn add<EMAIL_ADDRESS>vue-cli-service test:unit; yarn remove babel-core"

Amused me and does not make my tests that much longer.

Also found I could remove the need for<EMAIL_ADDRESS>if I used node v10

Rrrr... I found something else. If the component to be tested is inside the test folder, then I can import it. If it is in the src folder, I can't.
This doesn't work
import ControlHelpIcon from<EMAIL_ADDRESS>I copied the component into the same folder as the .spec.js file and imported it like this:
import ControlHelpIcon from './MyCompoentToTest.vue'
Why?
My config:
  "babel": {
    "plugins": [
      "@babel/plugin-syntax-jsx",
      "@babel/plugin-syntax-dynamic-import",
      "@babel/plugin-transform-spread",
      "@babel/plugin-proposal-object-rest-spread"
    ],
    "env": {
      "test": {
        "plugins": [
          "transform-es2015-modules-commonjs"
        ],
        "presets": [
          [
            "@babel/preset-env",
            {
              "modules": false
            }
          ]
        ]
      }
    }
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "vue"
    ],
    "snapshotSerializers": [
      "jest-serializer-vue"
    ],
    "transform": {
      "^.+\\.js$": "babel-jest",
      ".*\\.(vue)$": "vue-jest"
    }
  }

Answering my own question: the test folder needs to be inside the src folder.

@igasparetto Your jest configuration is missing the module name mapper:
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  }

This tells jest what URLs starting with "@" (i.e<EMAIL_ADDRESS>are supposed to mean. During normal builds this is mapped using resolve.alias in the webpack configuration, but this config is not shared with jest, so it has to be explicitly declared in moduleNameMapper as shown above. :)

@jonaskuske, indeed.
I have made so many changes trying to get this to a working stage that that was deleted.
Thanks

I just ran across this today.  My test were previous working with the first set of dependencies.  Yesterday I bumped all my dependency versions to the latest (2nd set) and noticed my test would no longer run because of the import issue discussed.  I've tried all the above suggestions to no avail.
    "@vue/cli-plugin-babel": "^3.1.1",
    "@vue/cli-plugin-eslint": "^3.1.5",
    "@vue/cli-plugin-unit-jest": "^3.1.1",
    "@vue/cli-service": "^3.1.4",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-jest": "^23.6.0",
    "eslint-plugin-vue": "^5.0.0-0",
    "node-sass": "^4.9.0",
    "replace": "0.3.0",
    "sass-loader": "^7.0.1",
    "vue-template-compiler": "^2.5.17"

    "@vue/cli-plugin-babel": "^3.4.0",
    "@vue/cli-plugin-eslint": "^3.4.0",
    "@vue/cli-plugin-unit-jest": "^3.4.0",
    "@vue/cli-service": "^3.4.0",
    "@vue/test-utils": "^1.0.0-beta.29",
    "babel-jest": "^24.1.0",
    "eslint-plugin-vue": "^5.2.2",
    "node-sass": "^4.11.0",
    "replace": "^1.0.1",
    "sass-loader": "^7.1.0",
    "vue-template-compiler": "^2.6.6"

I narrowed it down to the upgrade from babel-jest 23.6.0 to 24.1.0.  There is a similar error report here https://github.com/facebook/jest/issues/7957 and here https://github.com/facebook/jest/issues/7271.  @runarberg suggested this same resolution above.

Current state for me.
If I add a .babelrc file containing
{
  "presets": ["env"]
}

to my test/unit folder I get past the import issue instead getting
$ yarn test:unit
yarn run v1.13.0
$ vue-cli-service test:unit
 FAIL  tests/unit/cv-tag.spec.js
  ● Test suite failed to run

    Plugin 1 specified in<EMAIL_ADDRESS>provided an invalid property of "default" (While processing preset<EMAIL_ADDRESS>
      at Plugin.init (node_modules/babel-core/lib/transformation/plugin.js:131:13)
      at Function.normalisePlugin (node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
          at Array.map (<anonymous>)
      at Function.normalisePlugins (node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.738s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

 Package.json dependencies as below
  "dependencies": {
    "carbon-components": "^9.48.1",
    "d3": "^5.7.0",
    "flatpickr": "4.5.1",
    "vue": "^2.5.21"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@commitlint/cli": "^7.2.1",
    "@commitlint/config-conventional": "^7.1.2",
    "@storybook/addon-actions": "^4.1.11",
    "@storybook/addon-knobs": "^4.1.11",
    "@storybook/addon-notes": "^4.1.11",
    "@storybook/addon-options": "^4.1.11",
    "@storybook/addon-storysource": "^4.1.11",
    "@storybook/vue": "^4.1.11",
    "@vue/cli-plugin-babel": "^3.4.0",
    "@vue/cli-plugin-eslint": "^3.4.0",
    "@vue/cli-plugin-unit-jest": "^3.4.0",
    "@vue/cli-service": "^3.4.0",
    "@vue/eslint-config-prettier": "^4.0.1",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^24.1.0",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-object-rest-spread": "7.0.0-beta.3",
    "babel-preset-env": "^1.7.0",
    "babel-preset-vue": "^2.0.2",
    "eslint": "^5.10.0",
    "eslint-plugin-vue": "^5.0.0-0",
    "husky": "^1.3.0",
    "jest": "^24.1.0",
    "jest-config": "^24.1.0",
    "jest-runtime": "^24.1.0",
    "jest-serializer-vue": "^2.0.2",
    "jest-transform-stub": "^2.0.0",
    "lint-staged": "^8.1.0",
    "node-sass": "^4.11.0",
    "prettier": "^1.15.3",
    "sass-loader": "^7.1.0",
    "stylelint": "^9.9.0",
    "stylelint-config-property-sort-order-smacss": "^4.0.1",
    "stylelint-config-sass-guidelines": "^5.3.0",
    "vue-highlightjs": "^1.3.3",
    "vue-jest": "^3.0.2",
    "vue-loader": "^15.4.2",
    "vue-template-compiler": "^2.5.21"
  },

Unfortunately this kills my build so I have to uninstall between tests.
NOTE: After uninstalling babel-core the tests still run! This is because babel-jest has cached the file transformations. Clearing jest cache or editing a component will cause it to fail again.

This seems to be the main culprit: "babel-jest": "^24.1.0",

The same issue

If you use Vue CLI to create a new project and run “npm run test:unit” without changing anything, the tests will work. I believe the issue is that you project has newer versions of some dependencies because they have ~ or ^ in front of their versions which allow newer versions to be installed. If you pin to the same versions used in the new, working project then it should work. In particular, upgrading babel-jest to 24.1.0 will break the ability to run the unit tests.

which library versions (babel-jest etc..) should I use to make it run?

I believe the issue is that you project has newer versions of some dependencies because they have ~ or ^ in front of their versions which allow newer versions to be installed.

You can't "accidentally" upgrae to a new major version for babel-jest, the version range we set when creating a project is "^23.*".
Installing a new major release of any dependency might break a project as by definition, major releases (can) contain breaking changes.

which library versions (babel-jest etc..) and babelrc settings should I use to make it run?

@vue/cli-unit-jest currently relys on jest and babel-jest 23.*

@vue/cli-unit-jest

npm ERR! code E404
npm ERR! 404 Not Found: @vue/cli-unit-jest@latest

Not accidentally, but I think a lot of people periodically delete
package-lock.json and run "npm install" because they want to see if their
app will work with newer versions of libraries. In most cases that works
out, but this one where something bad happens.
On Mon, Mar 4, 2019 at 5:57 AM Thorsten Lünborg<EMAIL_ADDRESS>wrote:

I believe the issue is that you project has newer versions of some
dependencies because they have ~ or ^ in front of their versions which
allow newer versions to be installed.
You can't "accidentally" upgrae to a new major version for babel-jest, the
version range we set when creating a project is "^23.*".
Installing a new major release of any dependency might break a project as
by definition, major releases (can) contain breaking changes.
which library versions (babel-jest etc..) and babelrc settings should I
use to make it run?
@vue/cli-unit-jest currently relys on jest and babel-jest 23.*
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/vuejs/vue-cli/issues/1584#issuecomment-469226754, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AAE10MRLl1wFR2ASfhATcWke5Qg44ducks5vTQoQgaJpZM4UpzDz
.

--
R. Mark Volkmann
Object Computing, Inc.

No, you can't accidentally update to a new major version 24 when package.json has it defined as ^23.*. The ^ tells npm to only keep it inside of the 23.* version range.

Ah, this is an issue with me and perhaps others blindly accepting the
recommendations from a particular VS Code plugin. There is one called
"Version Lens" that shows the latest version of each dependency with
viewing a package.json file. If you click on the links it provides, it
changes the dependency version to the latest, completely ignoring the ^ and
~ characters. Lesson learned ... don't do that.
On Mon, Mar 4, 2019 at 9:32 AM Thorsten Lünborg<EMAIL_ADDRESS>wrote:

No, you can't accidentally update to a new major version 24 when
package.json has it defined as ^23.. The ^ tells npm to only keep it
inside of the 23. version range.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/vuejs/vue-cli/issues/1584#issuecomment-469295459, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AAE10DAHyen52dTkLhR9A0VyTNgzjDQZks5vTTx6gaJpZM4UpzDz
.

--
R. Mark Volkmann
Object Computing, Inc.

Semantic versioning has a purpose :smile_cat:

For me the following did the trick:
$ npm i<EMAIL_ADDRESS>$ npx jest --clearCache
$ npm t

If that doesn't work, delete node_modules and package-lock.json, and then run npm i again.

By doing npx jest --clearCache I fixed the issue somehow

Having the same problem, none of the above suggestions resolved the problem for me.
What is extra weird is that at some point we did not have this issue, CI succeeded 3 months ago but fails nowadays. We do not use a package-lock.json (yet), thus a small difference in versioning from the more 'loose' package.json made the issue arise...
Packages installed:

  "dependencies": {
    "@handsontable-pro/vue": "^3.0.0",
    "@vue/cli-plugin-unit-jest": "^3.5.3",
    "handsontable-pro": "^6.1.1",
    "jest": "^23.6.0",
    "jest-serializer-vue": "^2.0.2",
    "jest-transform-stub": "^2.0.0",
    "lodash": "^4.17.11",
    "moment": "^2.22.2",
    "register-service-worker": "^1.5.2",
    "vue": "^2.5.16",
    "vue-cookie": "^1.1.4",
    "vue-i18n": "^8.3.0",
    "vue-jest": "^3.0.4",
    "vue-js-modal": "^1.3.26",
    "vue-resource": "^1.5.1",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/polyfill": "^7.0.0",
    "@babel/runtime": "^7.0.0-beta.55",
    "@vue/cli-plugin-babel": "^3.2.0",
    "@vue/cli-plugin-eslint": "^3.0.0-rc.10",
    "@vue/cli-plugin-pwa": "^3.0.0-rc.10",
    "@vue/cli-service": "^3.0.0-rc.10",
    "@vue/eslint-config-standard": "^3.0.5",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "cache-loader": "^1.2.5",
    "eslint": "^5.10.0",
    "less": "^3.8.1",
    "less-loader": "^4.1.0",
    "ol": "^5.3.1",
    "proj4": "^2.5.0",
    "vue-template-compiler": "^2.5.16"
  },

(Sadly no package-lock.json)
Jest config:
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(!ol)'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^handsontable': 'handsontable'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  testURL: 'http://localhost/',
  verbose: true
}

I noticed someone had this in their Babel config.
"env": {
      "test": {
        "plugins": [
          "transform-es2015-modules-commonjs"
        ],
        "presets": [
          [
            "@babel/preset-env",
            {
              "modules": false
            }
          ]
        ]
      }
    }

Which requires the NODE_ENV environment variable to be set to test. Try running NODE_ENV=test;npm run test:unit

Here's the babel.config.js that's working for me:
module.exports = function(babel) {
  babel.cache(true);

  return {
    "presets": [["@babel/env", { "modules": false }]],
    "env": {
      "test": {
        "presets": [["@babel/env", { "targets": { "node": "current" } }]]
      }
    }
  };
};

If it helps, here's an example of a working repo with tests.

@RichAyotte Jest already sets NODE_ENV=test under the hood. See https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L13

@ericmdantas only if it's not already set. I've got NODE_ENV=development in my .bashrc. Shouldn't I be able to run test in my dev environment?

NODE_ENV=development in my .bashrc

That's a pretty bad idea.

Interesting, why is it a bad idea to do that on my dev box?

Well, because Vue CLI respects your system's env vars, which means, for example, that running this command on your dev system:
vue-cli-service build

Would not do what you expect it to - it would basically behave as if you ran
vue-cli-service build --mode development

This is a setup just waiting to cause confusion because something "works on my machine" but not yours. We would beoth write "But i do the same thing: vue-cli-service build! That's so weird".
I could even clone your repository and would still not be able to fully reproduce what you are doing unless you remember that you have this env variable defined in your .bashrc

In that case Vue CLI is not respecting my system's env vars. If it did, vue-cli-service build would consider my env and if it found that I had set my NODE_ENV then it would use its value unless the --mode was used to override.

But that's precisely what it does, and the problem I'm trying to describe:
vue-cli-service build sets NODE_ENV=production as a default, unless it's already specified
So on your system vue-cli-service build runs with NODE_NV=development, while it runs with NODE_ENV=production on mine.  We have the same project cloned, we run the same command, but two different things happen.
Doesn't this seem like a problem to you?

So on your system vue-cli-service build runs with NODE_NV=development, while it runs with NODE_ENV=production on mine. We have the same project cloned, we run the same command, but two different things happen.
Doesn't this seem like a problem to you?

If by the same command you mean just vue-cli-service build without the --mode override then no, it's not a problem. Otherwise there's no point in using an environment variable. The environment variable is precisely to provide the ability to build differently based on the environment that it's running in.

I guess we have to disgree. I just think it's a bad idea to have implicit dependencies like that. Makes it harder to cooperate.

To be clear, when I set the default NODE_ENV to development on my dev box and the default NODE_ENV to production on my prod box, it's explicit, not implicit.

@ericmdantas, thank you so much for pointing us to your vue-floating-alert repo! I spent too many hours today trying to figure out how to get imports working in my Jest test. None of the official documentation I looked at helped me (unless I was reading it all wrong). But then I tried mimicking your configuration, and it seems to be working perfectly! I can't thank you enough.

@kurtamohler I'm glad it helped 👍

I just ran into this problem. My fix was:
💡 Create a brand new project using vue-cli and then look at the git diff in the above mentioned files (package.json, jes.config.js, etc) My babel-jest ended up needed to be downgraded and babel-core needed to be upgraded. Jest now transforms correctly.
Thanks to the commenters above for blazing the trail!

@codyolsen  to which version you downgraded the the babel-core

The problem for me was that script tags were missing the "lang" attribute (this happened after installing Vuetify with 'vue add vuetify', which replace some files). Using <script lang="ts"> solved the problem for me.

Been running into this problem off and on for about a year.
It was totally my fault (that goes without saying 😄).
Every once in a while I like to go through and update all my dependencies. I actually use a tool, ncu to help. And it does its job a little too good sometimes ha. What'll happen is my "babel-jest": "^23.6.0", devDependency turns into "babel-jest": "^24.8.0", which of course seems to carry the issue with it.
So for me, that making sure babel-jest is on ^23.6.0. I know the op maybe didn't update the deps manually - but maybe something funky happened somehow.

@johndatserakis What do you even mean "babel-jest"? I only have "jest": "^24.8.0" also why is every npm package now babel-abc or babel/abc @babel/abc or babel ... so confusing

babel-jest is a tranform plugin for jest that allows jest to transform javascript with babel before running it.
It's pretty important since Vue projects usually use ES Modules and jest, being a node-based runner, can only consume commonjs modules.

@samayo http://lmgtfy.com/?q=babel-jest

@kurtamohler Thanks. It's just there is so much change in the front-end and not enough time to keep up.

After reading this and trying various configs, I still can't get jest to run with import statements in my nuxt app.
tests/models/Product.spec.js
import Product from<EMAIL_ADDRESS>
describe('Product Constructor', () => {
  it('Can create a product via the constructor', () => {
    // eslint-disable-next-line
    const product = new Product()
    expect(Product).toHaveBeenCalledTimes(1)
  })
})

/models/Product.js
export default class Product {
  constructor() {
    this.hello = 'world'
  }
}

.babelrc
{
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"],
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "node": "current"
            }
          }
        ],
        "@nuxt/babel-preset-app"
      ]
    }
  }
}

jest.config.js
module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '^vue$': 'vue/dist/vue.common.js'
  },
  moduleFileExtensions: ['js', 'vue', 'json'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  }
}

Whats missing? I'm using the create-nuxt-app defaults, referred to the nuxt, vue and jest docs but I'm just lost 🤷♂

Having moduleFileExtensions: ["js", "json", "vue"] in the config helped jest parse the .vue file imports—resolving this 'import' error.

transform: {
    “^.+\\.jsx?$”: “<rootDir>/node_modules/babel-jest”,

this one was helpful for me:
https://github.com/vuejs/vue-test-utils/issues/1011#issuecomment-502364518

In my case with nuxt, it was the create-nuxt-app creating a .babelrc file which did not work.
Fixed in future versions.
https://github.com/nuxt/create-nuxt-app/pull/193

Would like to report what worked for my particular project.
The problem I was seeing:
jest test ran fine using node_modules/.bin/jest but was was failing with "Unexpected identifier" error on import when running vue-cli-service test:unit:
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Vuex from 'vuex';
                                                                                ^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

After a lot of trial and error, was able to fix it.  First, here are the many things that didn't work:

Changing jest transform regex.  Line debugging confirmed that the issue wasn't that the test file wasn't being transformed using babel.  It was.
Clearing jest cache.
Running vue-cli-service test:unit using --no-cache.
Clearing yarn cache and rebuilding node_modules/ from scratch.
Downgrading babel-jest to 23.6.0 and later 23.4.2.
Changing jest transform babel-jest path from babel-jest to <rootDir>/node_modules/babel-jest
.babel.config.js change from this earlier comment
Copying <rootDir>/babel.config.js to tests/unit/ and then later tests/unit/store/ (where failing test file store.test.js was)
Re-ordering jest transform key/values as suggested in this earlier comment
Removing ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub", from jest transform configuration

I created a brand new project using Vue CLI 3.2.1 and found that the automatically created sample jest test worked with an import statement.
Compared the jest config of this newly created project to what I had.  After some experimentation, found that adding "babel-core": "7.0.0-bridge.0" to devDependencies was all I needed to clear the error.  This fix has been reported in this thread.

    },

The jest configuration (in package.json):
"jest": {
        "moduleFileExtensions": [
            "js",
            "jsx",
            "json",
            "vue"
        ],
        "moduleNameMapper": {
            "^@/(.*)$": "<rootDir>/src/$1"
        },
        "notify": true,
        "notifyMode": "always",
        "snapshotSerializers": [
            "jest-serializer-vue"
        ],
        "testMatch": [
            "**/tests/unit/**/*.test.(js|jsx|ts|tsx)"
        ],
        "testURL": "http://localhost/",
        "transform": {
            "^.+\\.vue$": "vue-jest",
            ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
            "^.+\\.jsx?$": "babel-jest"
        },
        "transformIgnorePatterns": [
            "/node_modules/"
        ],
        "watchPlugins": [
            "jest-watch-typeahead/filename",
            "jest-watch-typeahead/testname"
        ],
        "verbose": true
    }

OS: Macos 10.14.3
Node version: v10.12.0
NPM version: v6.4.1
For the vuejs/vue-cli devs who are having problems reproducing this bug: simply removing "babel-core": "7.0.0-bridge.0", from a project with devDependencies set to above and refreshing node_modules should reproduce the problem.  I tested this in my project and was able to recreate the import error.
I am guessing you could also just use Vue CLI 3.2.1 to create a basic project (selecting jest for unit tests) and remove "babel-core": "7.0.0-bridge.0", from it and rebuild.
Hope this helps.

Just now managed to reproduce the bug by creating a new project using Vue CLI 3.2.1 and changing babel-core version from 7.0.0-bridge.0 to 7.0.0-beta.3.
/tmp/> vue --version
3.2.1
/tmp/> vue create vue-cli-github-issue-1584

Vue CLI v3.2.1
┌───────────────────────────┐
│  Update available: 3.8.4  │
└───────────────────────────┘
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Unit
? Pick a unit testing solution: Jest
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? No

Vue CLI v3.2.1
✨  Creating project in /private/tmp/vue-cli-github-issue-1584.
🗃  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...

yarn install v1.13.0
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...

success Saved lockfile.
✨  Done in 12.36s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.13.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
✨  Done in 4.27s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project vue-cli-github-issue-1584.
👉  Get started with the following commands:

 $ cd vue-cli-github-issue-1584
 $ yarn serve

/tmp/> cd vue-cli-github-issue-1584/
/tmp/vue-cli-github-issue-1584/> yarn upgrade<EMAIL_ADDRESS>yarn upgrade v1.13.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Rebuilding all packages...
success Saved lockfile.
success Saved 4 new dependencies.
info Direct dependencies
└─<EMAIL_ADDRESS>info All dependencies
├─<EMAIL_ADDRESS>├─<EMAIL_ADDRESS>├─<EMAIL_ADDRESS>└─<EMAIL_ADDRESS>✨  Done in 5.93s.
/tmp/vue-cli-github-issue-1584/> yarn test:unit --no-cache
yarn run v1.13.0
$ vue-cli-service test:unit --no-cache
 FAIL  tests/unit/example.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /private/tmp/vue-cli-github-issue-1584/tests/unit/example.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '@vue/test-utils';
                                                                                ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.575s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
/tmp/vue-cli-github-issue-1584/> cat package.json
{
  "name": "vue-cli-github-issue-1584",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
    "core-js": "^2.6.5",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-plugin-unit-jest": "^3.8.0",
    "@vue/cli-service": "^3.8.0",
    "@vue/test-utils": "1.0.0-beta.29",
    "babel-core": "7.0.0-beta.3",
    "babel-jest": "^23.6.0",
    "vue-template-compiler": "^2.6.10"
  }
}
/tmp/vue-cli-github-issue-1584/> yarn upgrade<EMAIL_ADDRESS>yarn upgrade v1.13.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " ><EMAIL_ADDRESS>has unmet peer dependency "<EMAIL_ADDRESS>[4/4] 🔨  Rebuilding all packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─<EMAIL_ADDRESS>info All dependencies
└─<EMAIL_ADDRESS>✨  Done in 5.57s.
/tmp/vue-cli-github-issue-1584/> yarn test:unit --no-cache
yarn run v1.13.0
$ vue-cli-service test:unit --no-cache
 PASS  tests/unit/example.spec.js
  HelloWorld.vue
    ✓ renders props.msg when passed (37ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.738s
Ran all test suites.
✨  Done in 2.96s.
/tmp/vue-cli-github-issue-1584/> cat package.json
{
  "name": "vue-cli-github-issue-1584",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
    "core-js": "^2.6.5",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-plugin-unit-jest": "^3.8.0",
    "@vue/cli-service": "^3.8.0",
    "@vue/test-utils": "1.0.0-beta.29",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "vue-template-compiler": "^2.6.10"
  }
}
/tmp/vue-cli-github-issue-1584/>

I created a brand new project using vue-cli v3.8.4 and included unit testing with Jest. Running the included Jest test using the test:unit npm script, it completes fine:
 PASS  tests/unit/example.spec.js
  HelloWorld.vue
    √ renders props.msg when passed (21ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.629s
Ran all test suites.

Attempting to debug the test with VSCode with the following configuration mentioned in various articles...
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Jest Tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect-brk",
        "${workspaceRoot}/node_modules/jest/bin/jest.js",
        "--runInBand"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "port": 9229
    }
  ]
}

I run into the following error:

 FAIL  tests/unit/example.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\SRC\Apps\fresh-proj\tests\unit\example.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from "@vue/test-utils";
                                                                                ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        5.455s
Ran all test suites.
Waiting for the debugger to disconnect...

Thus far the vue-cli-service test:unit command seems reliable (albeit I've had to clear Jest's cache to cleanup whatever the debugger command messed up), but I cannot get the VSCode debugger command to work reliably.

npx jest --clearCache
works for me.

I'm getting this now, Have read pretty much all this issue now. Any tips?
cat jest.config.js
module.exports = {
  moduleFileExtensions: ["js", "jsx", "json", "vue"],
  transform: {
    "^.+\\.vue$": "vue-jest",
    ".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$":
      "jest-transform-stub",
    "^.+\\.jsx?$": "babel-jest"
  },
  transformIgnorePatterns: ["/node_modules/"],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  snapshotSerializers: ["jest-serializer-vue"],
  testMatch: [
    "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
  ],
  testURL: "http://localhost/",
  watchPlugins: [
    "jest-watch-typeahead/filename",
    "jest-watch-typeahead/testname"
  ],
  coverageDirectory: "<rootDir>/tests/unit/coverage",
  collectCoverageFrom: [
    "src/**/*.{js,vue}",
    "!src/main.js",
    "!src/router/index.js",
    "!**/node_modules/**"
  ]
}

Error:
tests/unit/Dashboard.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { createLocalVue, shallowMount } from "@vue/test-utils";
                                                                                ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/@vue/cli-plugin-unit-jest/node_modules/jest-runtime/build/script_transformer.js:403:17)

I'll try a brand new project via latest vue cli 3 and copy a component across and corresponding test and see if it's my set up.

@ghenry: you can first try adding "babel-core": "7.0.0-bridge.0" to devDependencies and see if that fixes your problem (or changing the version of babel-core if it's already installed).  This might happen automatically when scaffolding with the latest Vue CLI 3, but if you don't want to go through the trouble of migrating to a new project, you can try this manual fix first.  Possibly there are versions later than "7.0.0-bridge.0" that would also work, but might want to stick to "7.0.0-bridge.0" for the first trial.

Damn, I already have that:
 "devDependencies": {
    "@vue/cli-plugin-babel": "^3.9.2",
    "@vue/cli-plugin-e2e-nightwatch": "^3.9.2",
    "@vue/cli-plugin-eslint": "^3.9.2",
    "@vue/cli-plugin-unit-jest": "^3.9.0",
    "@vue/cli-service": "^3.9.3",
    "@vue/eslint-config-prettier": "^4.0.1",
    "@vue/test-utils": "^1.0.0-beta.29",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^10.0.2",
    "babel-jest": "^24.8.0",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "eslint": "^5.16.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.0",
    "eslint-plugin-vue": "^5.2.3",
    "git-revision-webpack-plugin": "^3.0.3",
    "jest": "^24.8.0",
    "lint-staged": "^8.2.1",
    "node-sass": "^4.12.0",
    "sass-loader": "^7.0.1",
    "vue-template-compiler": "^2.6.10",
    "yorkie": "^2.0.0"
  },

I posted the devDependencies from my working project in earlier comment, and I notice differences from yours.  You are not using the @babel/* packages, for example.  It might be worth trying your code in a new project after all, to make sure you have the right combination of packages.
I do notice your error is not occurring on import, but on the { after it.  Not sure if that is significant.

Thanks @da70 I think I'll try a new project as I've never had @babel before and I just tested adding those. No joy.

All my tests are based on https://www.manning.com/books/testing-vue-js-applications and I have a sanity test like so which is OK and runs/passes:
cat tests/unit/sanity_check.spec.js
test("sanity test", () => {
  expect(true).toBe(true)
})

Thanks.

Weirdly I'm now getting:
Details:

   tests/unit/About.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { createLocalVue, shallowMount } from "@vue/test-utils";
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

on the import, not {

So, if I create a new project with vue-cli 3.10.0 and copy my About.spec.js and About.vue into it, updating my package.json to add bootstrap-vue, all works. That's something!
Will report back after some diffing.

Figured it out via a new project via vue cli 3.10.0. If you upgrade babel-jest to 24.x.x this happens:
/home/ghenry/vue-testing/tests/unit/About.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { createLocalVue, shallowMount } from "@vue/test-utils";
                                                                                ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

as soon as I use what vue cli 3.10.0 or earlier creates, i.e. babel-jest < 24.x.x, my tests run. Can you verify for me @da70 ?
P.S. I needed bootstrap-vue for my test to run, so please ignore that.
diff --git a/package.json b/package.json
index b1b2aab..74072a5 100644
--- a/package.json
+++ b/package.json
@@ -10,6 +10,7 @@
     "test:unit": "vue-cli-service test:unit"
   },
   "dependencies": {
+    "bootstrap-vue": "^2.0.0-rc.27",
     "core-js": "^2.6.5",
     "vue": "^2.6.10",
     "vue-router": "^3.0.3",
@@ -25,7 +26,7 @@
     "@vue/test-utils": "1.0.0-beta.29",
     "babel-core": "7.0.0-bridge.0",
     "babel-eslint": "^10.0.1",
-    "babel-jest": "^23.6.0",
+    "babel-jest": "^24.8.0",
     "eslint": "^5.16.0",
     "eslint-plugin-prettier": "^3.1.0",
     "eslint-plugin-vue": "^5.0.0",

Maybe of help for those getting this specific type of error. Note I'm not using vue, but landed here looking up the error notice:
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import myImport from '../../src/index';
                                                                                ^^^^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

I think if you have the latest jest and @babel, you may not even need babel-jest. You just need it to be spotting your babel config. I had misplaced my .babelrc and so was getting that error. Before I realised, I'd tried a number of the above with no success. When I restored it to the right place (project root), it just worked(tm).
My relevant devDeps looks like:
"@babel/cli": "^7.5.5",
"@babel/core": "^7.5.5",
"@babel/plugin-transform-modules-commonjs": "^7.5.0",
"@babel/preset-env": "^7.5.5",
"jest": "^24.8.0"

My .babelrc looks like:
{
  "presets": [
    [ "@babel/preset-env", {
      "targets": { "node": "10" }
    } ]
  ],
  "plugins": [ "@babel/plugin-transform-modules-commonjs" ]
}

HTH :)

✅ This fixed it for me:

rm -rf node_modules
downgrade to babel-jest 23.6
IMPORTANT rm package-lock.json
run npm install

Thanks to https://github.com/facebook/jest/issues/6229#issuecomment-514343548

I am facing this problem.
package.json
"dependencies": {
    "@download/blockies": "^1.0.3",
    "axios": "^0.19.0",
    "buefy": "^0.7.7",
    "qrcode.vue": "^1.6.2",
    "store": "^2.0.12",
    "vue": "^2.6.10",
    "vue-clipboard2": "^0.3.0",
    "vue-element-loading": "^1.1.1",
    "vue-loading-template": "^1.3.2",
    "vue-qrcode-reader": "^2.0.1",
    "vue-router": "^3.0.6",
    "vue-social-sharing": "^2.4.5",
    "vuex": "^3.1.1"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.5.5",
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-plugin-eslint": "^3.8.0",
    "@vue/cli-service": "^3.8.4",
    "@vue/eslint-config-standard": "^3.0.5",
    "@vue/test-utils": "^1.0.0-beta.29",
    "babel-jest": "23.6.0",
    "jest": "^24.8.0",
    "jest-serializer-vue": "^2.0.2",
    "jest-transform-stub": "^2.0.0",
    "node-sass": "^4.12.0",
    "sass": "^1.22.0",
    "sass-loader": "^7.1.0",
    "vue-jest": "^3.0.4",
    "vue-template-compiler": "^2.6.10"
  }

babel.config.js
module.exports = {
  presets: [
    '@vue/app'
  ],
  env: {
    test: {
      presets: [['@babel/preset-env']]
    }
  }
}

jest.config.js
module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.js$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
  ],
  transformIgnorePatterns: ['<rootDir>/node_modules/']
}

Weirdly I'm now getting:
Details:

   tests/unit/About.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { createLocalVue, shallowMount } from "@vue/test-utils";
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

on the import, not {

We are having a very similar behavior. But we are getting the error on the import and on { at same time.
This Shows on Linux and WSL (Ubuntu)
Details:
    /mnt/d/repos/phoenix/node_modules/@vilynx/frontend-core/localstorage.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { StorageFormat } from './enums/storage';
                                                                                ^^^^^^

    SyntaxError: Unexpected token import

This shows up on Windows (cmd)
    D:\repos\phoenix\node_modules\@vilynx\frontend-core\localstorage.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { StorageFormat } from './enums/storage';
                                                                                ^

    SyntaxError: Unexpected token {

🤷♂
However, if we only use .ts it works fine, the problem comes when a JS gets imported.

@ghenry, I was on vacation and didn't see your query until I got back today.  Not sure if you are still having issues, but you wrote:

as soon as I use what vue cli 3.10.0 or earlier creates, i.e. babel-jest < 24.x.x, my tests run. Can you verify for me @da70 ?

I use babel-jest 24.8.0 in my working project, and don't have any problems.  See [earlier comment].
Your babel-core and babel-eslint match mine.  I assume you also have @babel/* packages?
I used Vue CLI 3.2.1, not 3.10.0, so not sure if that makes a difference.  I couldn't be sure from your comment, but it seemed like you were saying that Vue CLI 3.10.0 was using babel-jest version lower than 24.x.x by default?

Hey, folks. I posted a question about this issue in the Vue Forum and ended up finding a solution that worked for me. This thread is partly to thank for giving me ideas of things to try, but if you're interested in following my specific steps, I've outlined them here:
https://forum.vuejs.org/t/jest-unit-tests-not-working/73334/4
Best of luck to all of you!

Thanks da70. I'm all working now given what I posted. Not spent any more
time on it as all my tests are passing in gitlab ci.

@ghenry: great, glad to hear it.

Maybe of help for those getting this specific type of error. Note I'm not using vue, but landed here looking up the error notice:
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import myImport from '../../src/index';
                                                                                ^^^^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

I think if you have the latest jest and @babel, you may not even need babel-jest. You just need it to be spotting your babel config. I had misplaced my .babelrc and so was getting that error. Before I realised, I'd tried a number of the above with no success. When I restored it to the right place (project root), it just worked(tm).
My relevant devDeps looks like:
"@babel/cli": "^7.5.5",
"@babel/core": "^7.5.5",
"@babel/plugin-transform-modules-commonjs": "^7.5.0",
"@babel/preset-env": "^7.5.5",
"jest": "^24.8.0"

My .babelrc looks like:
{
  "presets": [
    [ "@babel/preset-env", {
      "targets": { "node": "10" }
    } ]
  ],
  "plugins": [ "@babel/plugin-transform-modules-commonjs" ]
}

HTH :)

Thanks, It works for me

@mika76 Try the 4.0 RC. We've managed to move all the default boilerplates into jest presets. Now there's a @vue/cli-plugin-unit-jest/presets/typescript preset. See https://github.com/vuejs/vue-cli/releases/tag/v4.0.0-rc.4 for more details.

@sodatea That looks highly relevant, but when I try @vue/cli-plugin-unit-jest/presets/typescript or @vue/cli-plugin-unit-jest/presets/typescript-and-babel I get:
● Validation Error:

  Preset @vue/cli-plugin-unit-jest/presets/typescript not found.

And if I try just @vue/cli-plugin-unit-jest then I get:
● Validation Error:

  Module @vue/cli-plugin-unit-jest should have "jest-preset.js" or "jest-preset.json" file at the root.

To confirm, vue CLI version is 4.0.0-rc.6.

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include<EMAIL_ADDRESS>Do not skip this step and do not use any other version tag!
If you previously ran vue-cli-service test:unit without the above requirement, then you must run npx jest --clearCache. After that, Jest should start using babel-jest as expected.
I only figured this out after reading @vue/cli-plugin-unit-jest here: https://github.com/vuejs/vue-cli/blob/v3.11.0/packages/%40vue/cli-plugin-unit-jest/generator/index.js#L58

My project is working with yarn vue-cli-service test:unit but not yarn jest. It seems the jest plugin requires 2 env vars to work properly:
https://github.com/vuejs/vue-cli/blob/4f4aae2420f3b069566793bc3793a453bea5c5ff/packages/%40vue/cli-plugin-unit-jest/index.js#L13
env VUE_CLI_BABEL_TARGET_NODE=true VUE_CLI_BABEL_TRANSPILE_MODULES=true yarn jest is working for me. Still, must run yarn jest --clearCache first if you already face the issue.

@jameschenjav VueCLI might do more than setting those two environment variables in the future. You should always run Jest through vue-cli-service test:unit in order for configuration to be correct. Running Jest directly is not supported.

thanks @sirlancelot . Does that mean we could not take advantages of editors/ide, like vscode with jest extension shows test results on the fly? or vetur extension would take care of what jest does? currently, we can still have a workaround by setting those 2 vars.

I don't know for sure, but it might be worth discussing on Discord or the Forum.
For those looking for the fix for this issue: please see my comment above: https://github.com/vuejs/vue-cli/issues/1584#issuecomment-537150505

@sirlancelot https://github.com/vuejs/vue-cli/issues/1584#issuecomment-537150505
Thank you, this worked for me 🙏

I have<EMAIL_ADDRESS>dependency but still the same issue occurs.
This is my jest config:
module.exports = {   moduleFileExtensions: [     'js',     'jsx',     'json',     'vue',   ],   transform: {     '^.+\\.vue$': 'vue-jest',     '.+\\.(js|jsx|ts|tsx|css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':       'jest-transform-stub',     '^.+\\.jsx?$': 'babel-jest',   },   transformIgnorePatterns: [     '<rootDir>/(node_modules)/',   ],   moduleNameMapper: {     '^@/(.*)$': '<rootDir>/src/$1',   },   snapshotSerializers: [     'jest-serializer-vue',   ],   testMatch: [     '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)',   ],   testURL: 'http://localhost/', };

I have<EMAIL_ADDRESS>dependency but still the same issue occurs.
This is my jest config:

solved my issue by making babel.config.js to look like this:
module.exports = {
  presets: [
    '@vue/app',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env']],
    },
  },
};

This solves the issue for me
Add the following dependencies with yarn or npm or whatever you use
yarn add @babel/core @babel/preset-env or npm install --save-dev @babel/core @babel/preset-env
Create a new file called babel.config.js in the same directory as package.json.
Put the following content in it:
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ]
};

And then, import and other ES6 related features started working with jest.

JS ecosystem is a kind of dark magic...
I had the same problem. In my package.json I have a "jest" section with moduleFileExtensions setting. The jest documentation says

We recommend placing the extensions most commonly used in your project on the left

so, since I used TS, my moduleFileExtensions looked like this:
"moduleFileExtensions": [       "ts",       "vue",       "js",       "json"     ],
and I got error

Test suite failed to run
Jest encountered an unexpected token

...
Details:
D:\Projects\MyAwesomeProject\src\components\TheMap\LodControl.vue:2
import _classCallCheck from "d:\\Projects\\MyAwesomeProject\\node_modules\\@babel\\runtime-corejs2/helpers/esm/classCallCheck";
^^^^^^

SyntaxError: Unexpected token import

When I changed moduleFileExtensions  to
"moduleFileExtensions": [       "js",       "ts",       "json",       "vue"     ],
the error disappeared.

Maybe of help for those getting this specific type of error. Note I'm not using vue, but landed here looking up the error notice:
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import myImport from '../../src/index';
                                                                                ^^^^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

I think if you have the latest jest and @babel, you may not even need babel-jest. You just need it to be spotting your babel config. I had misplaced my .babelrc and so was getting that error. Before I realised, I'd tried a number of the above with no success. When I restored it to the right place (project root), it just worked(tm).
My relevant devDeps looks like:
"@babel/cli": "^7.5.5",
"@babel/core": "^7.5.5",
"@babel/plugin-transform-modules-commonjs": "^7.5.0",
"@babel/preset-env": "^7.5.5",
"jest": "^24.8.0"

My .babelrc looks like:
{
  "presets": [
    [ "@babel/preset-env", {
      "targets": { "node": "10" }
    } ]
  ],
  "plugins": [ "@babel/plugin-transform-modules-commonjs" ]
}

HTH :)

Adding .babelrc into my project root directory fixes the import problem.
My .babelrc looks like:

{
  "presets": [
    [ "@babel/preset-env", {
      "targets": { "node": "10" }
    } ]
  ],
  "plugins": [ "@babel/plugin-transform-modules-commonjs" ]
}

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import _Object$defineProperty from "../../core-js/object/define-property";
^^^^^^
SyntaxError: Cannot use import statement outside a module

  17 |             <template #selection="data">
  18 |               <v-chip :key="data.item.entity_id" :input-value="data.selected">
> 19 |                 <p>{{ data.item.display_name }}-{{ data.item.profile.emp_id }}-{{ data.item.profile.guard_id}}</p>
     |                                               ^
  20 |               </v-chip>
  21 |             </template>
  22 |           </v-autocomplete>

  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/ui/sections/Patrol/PatrolSupervisorValidationStatus.vue:19:47
  at Object.<anonymous> (src/ui/sections/Patrol/PatrolSupervisorValidationStatus.vue:166:3)

i am getting this error

I have<EMAIL_ADDRESS>dependency but still the same issue occurs.
This is my jest config:

solved my issue by making babel.config.js to look like this:
module.exports = {
  presets: [
    '@vue/app',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env']],
    },
  },
};

Update: strangely it works locally but the same error occurs after building in gitlab. All config files, packages and global dependencies are the same

@Zilvinaskli I wonder if your CLI problem was that the environment variable in your CLI was something other than test and thus accounts for the discrepancy you experienced.

This fix is working fine for me. Just add preset babel-preset-next to .babelrc file. jest is read .babelrc file from root directory.
For more information checkout this link: https://nextjs.org/docs/advanced-features/customizing-babel-config
{
  "presets": ["next/babel"]
}
``

    [       '@babel/preset-env',       {         modules: 'commonjs',       }     ]
commonjs is ok

its cannot find the import and getting this error
RUNS  src/tests/add.test.js
RUNS  src/tests/actions/expenses.test.js
FAIL  src/tests/actions/expenses.test.js
RUNS  src/tests/add.test.js
RUNS  src/tests/actions/expenses.test.js
● Test suite failed to run
Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

C:\expensify\src\tests\actions\expenses.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { addExpense, editExpense, removeExpense } from '../../actions/expenses';
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1085:14)

RUNS  src/tests/add.test.js
RUNS  src/tests/actions/expenses.test.js
RUNS  src/tests/add.test.js
RUNS  src/tests/actions/expenses.test.js
RUNS  src/tests/add.test.js
PASS  src/tests/add.test.js (5.007s)
RUNS  src/tests/add.test.js
Test Suites: 1 failed, 1 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.864s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

@onigunn Can't find the jest.config.js file!

Same error on Create React App with jest-puppeteer e2e test.
I replaced import statements to require and for CRA it works!
sign_in.test.js:
const signIn = require('./jest.sign_in')
describe('sign_in', () => {
  beforeEach(async () => {
    await page.goto('http://localhost:3000')
  })
 it('should log in auth form', async () => {
    try {
      await signIn(page)
    } catch (err) {
      console.warn(`Unexpected test error: ${err}`)
    }
  }, 4000)
})

jest.sign_in.js:
async function signIn (page) {
    await page.click('input[type=email]')
    await<EMAIL_ADDRESS>{delay: 10});
    await page.click('input[type=password]')
    await page.keyboard.type('Qwerty123!', {delay: 10});
    await page.keyboard.press('Enter');
    await page.waitFor(1000);
    await expect(page.url()).toMatch('/account')
}

module.exports = signIn

 [ '@babel/preset-env', { modules: 'commonjs', } ]
i meet this problem and solved id by setting 'modules' as 'commonjs' 😄

Surely it's a ES6 module syntax transpiling issue. Your solution, as mine goin to work for any boilerplate, I think. But i wont eject webpack from CRA and hasnt got .babelrc, babel.config and jest.config, as you, @mohsenuss91. Try to my solution
Just replace es6 import to commonjs require

@WebKieth I'm using VueJs and I'm trying with:
import { shallowMount } from '@vue/test-utils'
But still getting this:
`Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

D:\Users\PC01\school\tests\features\Unit.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '@vue/test-utils';
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1086:14)`

shallowMount

@mohsenuss91 aw, as u see I dont use built-in test utilities, I use puppeteer instructions - It's just another way to test. My React Tools dont do anything inside test scripts - so I dont import it. I import only required repeated actions.
When I need to test, I just turn on my dev server and run tests inside puppeteer session.

Is everyone here using windows? I didn't reproduce the error on mac.

@marcusnunes  I'm using windows10, and still got this :
`({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import { shallowMount } from '@vue/test-utils';
^^^^^^
SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1086:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.3s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR<EMAIL_ADDRESS>test: jest
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the<EMAIL_ADDRESS>test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
`
Here is my jest.config.js file:
module.exports = {     moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],     transform: {         "^.+\\.js$": "babel-jest",         ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"     },     moduleNameMapper: {         "^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"     },     snapshotSerializers: [         "<rootDir>/node_modules/jest-serializer-vue"     ],     testMatch: [         '<rootDir>/tests/**/*.spec.(js|jsx|ts|tsx)|<rootDir>/**/__tests__/*.(js|jsx|ts|tsx)'     ],     transformIgnorePatterns: ['<rootDir>/node_modules/'] };

I'm currently stuck on something I believe is related.
My components.spec.js contains the following basic test:
import { mount } from '@vue/test-utils'
import Quiz from<EMAIL_ADDRESS>
describe('Quiz', () => {
    test('is a Vue instance', () => {
        const wrapper = mount(Quiz)
        expect(wrapper.isVueInstance()).toBeTruthy()
    })
})

The Quiz.vue has the following imports:
.......
<script>
import { mapState } from 'vuex'
import Loading from '~/components/Quiz/Loading'
import QuizStep from '~/components/Quiz/Step'
import NameStep from '~/components/Quiz/StepType/Name'
import GradeStep from '~/components/Quiz/StepType/Grade'
.......

When I run jest I receive the following output:
$ yarn test
yarn run v1.22.4
$ jest
 FAIL  components/__tests__/components.spec.js
  ● Test suite failed to run

    Cannot find module '~/components/Quiz/Loading' from 'Quiz.vue'

    Require stack:
      components/Quiz.vue
      components/__tests__/components.spec.js

      38 | <script>
      39 | import { mapState } from 'vuex'
    > 40 | import Loading from '~/components/Quiz/Loading'
         | ^
      41 | import QuizStep from '~/components/Quiz/Step'
      42 | import NameStep from '~/components/Quiz/StepType/Name'
      43 | import GradeStep from '~/components/Quiz/StepType/Grade'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:299:11)
      at components/Quiz.vue:40:1
      at Object.<anonymous> (components/Quiz.vue:456:3)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.041s
Ran all test suites.

I have bashed my head the whole day trying to get it to work but nothing. I can provide further info/configs if required.
For tests on other components that do not have any imports from my components directory work fine. I'm confused (first time trying to implement unit tests)

@kaypon have you tried absolute paths and including the .vue extension?

@kaypon i have the same problem , did you solve it yet?

ES modules are not supported in Node. Because Jest is running in Node, when it hits this import statement, we're getting that syntax error.
.babelrc.js
presets: [
['@babel/preset-env', {modules: 'commonjs' }] , ....]

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include<EMAIL_ADDRESS>Do not skip this step and do not use any other version tag!
If you previously ran vue-cli-service test:unit without the above requirement, then you must run npx jest --clearCache. After that, Jest should start using babel-jest as expected.
I only figured this out after reading @vue/cli-plugin-unit-jest here: https://github.com/vuejs/vue-cli/blob/v3.11.0/packages/%40vue/cli-plugin-unit-jest/generator/index.js#L58

This worked for me, thank you!

I use vue-cli-service test:unit to run my test suites. npx jest --clearCache worked for me. Something funny was going on in cache..
Thanks!

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include<EMAIL_ADDRESS>Do not skip this step and do not use any other version tag!
If you previously ran vue-cli-service test:unit without the above requirement, then you must run npx jest --clearCache. After that, Jest should start using babel-jest as expected.
I only figured this out after reading @vue/cli-plugin-unit-jest here: https://github.com/vuejs/vue-cli/blob/v3.11.0/packages/%40vue/cli-plugin-unit-jest/generator/index.js#L58

None of this worked for me, i am using vuejs

This issue is over two years old now. It is very likely not "fixable" by the team per se. Most folks have found this comment to be the most helpful:

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include<EMAIL_ADDRESS>Do not skip this step and do not use any other version tag!
If you previously ran vue-cli-service test:unit without the above requirement, then you must run npx jest --clearCache. After that, Jest should start using babel-jest as expected.
I only figured this out after reading @vue/cli-plugin-unit-jest here: https://github.com/vuejs/vue-cli/blob/v3.11.0/packages/%40vue/cli-plugin-unit-jest/generator/index.js#L58

This is probably worth closing and locking with this as the last comment as it's far too broad. cc: @Akryum

The unfixable problem.

Test fail. SyntaxError: Cannot use import statement outside a module. at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14) Jest encountered an unexpected token. Babel config module.exports = {   presets: [     [       '@babel/preset-env',       {         targets: {           node: 'current',         },       },     ],   ],   plugins: ['@babel/plugin-proposal-class-properties'], }; Babel V7

Test fail. SyntaxError: Cannot use import statement outside a module. at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14) Jest encountered an unexpected token. Babel config module.exports = {   presets: [     [       '@babel/preset-env',       {         targets: {           node: 'current',         },       },     ],   ],   plugins: ['@babel/plugin-proposal-class-properties'], }; Babel V7

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include<EMAIL_ADDRESS>Do not skip this step and do not use any other version tag!
If you previously ran vue-cli-service test:unit without the above requirement, then you must run npx jest --clearCache. After that, Jest should start using babel-jest as expected.
I only figured this out after reading @vue/cli-plugin-unit-jest here: https://github.com/vuejs/vue-cli/blob/v3.11.0/packages/%40vue/cli-plugin-unit-jest/generator/index.js#L58

No go for me. Still stuck at SyntaxError: Cannot use import statement outside a module. If it's something got to do with CommonJS, I've also tried those workaround listed on this issue page but then again, no luck.
And yeah vue -V says @vue/cli 4.5.10. For Vue without Typescript, is there any solution to this yet?

A fix that worked for me: replace .babel.config.js by .babelrc :)

I am getting this error with webpack config, when it detects import {mod1, mod2,..} from 'modpath' (named imports) in modules.
Here is the webpack config:
module.exports = {
    entry: {
        'myapp': ['@babel/polyfill', 'whatwg-fetch', paths.appIndex]
    },
    module: {
        rules: [
            {
                test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
                loader: require.resolve('url-loader'),
                options: {
                    limit: 10000,
                    name: 'static/media/[name].[hash:8].[ext]'
                }
            },
            {
                enforce: 'pre',
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                loader: 'eslint-loader',
                options: {
                    cache: true,
                    fix: true,
                    configFile: './.eslintrc',
                }
            },
            {
                test: /\.(js|jsx)$/,
                include: [paths.appSrc, paths.appMrc],
                loader: 'babel-loader',
                options: {
                    cacheDirectory: true,
                    presets: ['@babel/preset-env', '@babel/preset-react'],
                    plugins: ['@babel/plugin-proposal-class-properties']
                }
            },
            {
                test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: require.resolve('file-loader'),
                        options: {
                            name: '[name].[hash:8].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    resolve: {
        modules: [paths.appNodeModules],
        alias: aliasConfig,
        extensions: ['*', '.js', '.jsx']
    },
    plugins: [
        // Generates an `index.html` file with the <script> injected.
        new HtmlWebpackPlugin({
            inject: true,
            template: paths.appHtml,
            filename: 'index.html'
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new webpack.DefinePlugin({
            VERSION: JSON.stringify(require('../package.json').version)
        })
    ],
    resolveLoader: {
        alias: {
            text: 'html-loader'
        }
    }
};

There is a preset option in there, where I added target but alas does not work.
jest.config.json:
moduleDirectories: [paths.appNodeModules, paths.appJs],
moduleFileExtensions: ['js', 'jsx'],
moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$': '<rootDir>/tests/__mocks__/fileMock.js',
        '\\.(css|scss)$': '<rootDir>/tests/__mocks__/styleMock.js',
        '^xyz-react-components(.*)$': '<rootDir>/node_modules/xyz-react-components/dist/$1',
        'xyz-session': '<rootDir>/tests/__mocks__/session.js',
        'xyz-i18n': '<rootDir>/tests/__mocks__/i18n.js',
        '@babel-polyfill': <EMAIL_ADDRESS>},
rootDir: '../',
roots: ['<rootDir>/tests'],
setupFiles: []

I'm getting this same error when I try to import json into my component.
Is there a way to just disable this feature?

Can't believe this issue is still open...
           ^^^^^^^^
    SyntaxError: Unexpected identifier```

Not sure what the status of this one is, but I think there is a simple solution that I haven't seen mentioned:
the only two things I needed to do for happy jest testing is: