vue-cli: 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

> test-application@0.1.0 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.

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 332
  • Comments: 249 (44 by maintainers)

Commits related to this issue

Most upvoted comments

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.

Same issue. None of the proposed solutions works for me

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/']
}

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.

Reproduced on mac here. For me it occurred after manually incremented all the @vue/* packages to rc.3 from one of the betas (beta.16 I think). I did a rm -rf node_modules && npm cache clean --force && npm install

^ began erroring.

What ended up working for me was globally installing the latest @vue/vue-cli (rc.3) and starting a new project. This also installed all rc.3 @vue/* packages but for some reason it no longer errored.

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
npm run test:unit
# ✓ 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 simply downgrading (npm install --save-dev babel-jest@23) will not fix the problem on its own. I had to remove node_modules and package-lock.json and clear the jest cache, before the tests would run again:

npm install --save-dev babel-jest@23
npx jest --clearCache
rm -fr node_modules package-lock.json
npm install

I was able to fix this issue by adding the following to the jest.config.js transform section:

'^.+\\.js$': 'babel-jest',

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

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.

Update: I’ve started to get the same thing again, so I had to run node node_modules/.bin/jest --clearCache to solve it.

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

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

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™. 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" ]
}

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' }] , ....]

npx jest --clearCache works for me.

For me the following did the trick:

$ npm i babel-core@7.0.0-bridge.0
$ npx jest --clearCache
$ npm t

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

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include babel-core@7.0.0-bridge.0. 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

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)

EDIT: Just noticed that the error I pasted in above is different from the “SyntaxError: Unexpected token import” in original post, but I’m pretty sure I’ve gotten that error too, just can’t find it my issue tracker. Also, see bug reproduction I put in following comment, which is does produce “SyntaxError: Unexpected token import” error.

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.

Here are the final relevant devDependencies for the working project:

"devDependencies": {
        "@babel/cli": "^7.4.4",
        "@babel/core": "^7.4.5",
        "@babel/preset-env": "^7.4.5",
        "@babel/register": "^7.4.4",
        "@vue/cli-plugin-babel": "^3.8.0",
        "@vue/cli-plugin-eslint": "^3.8.0",
        "@vue/cli-plugin-unit-jest": "^3.8.0",
        "@vue/cli-service": "^3.8.4",
        "@vue/eslint-config-standard": "^4.0.0",
        "@vue/test-utils": "^1.0.0-beta.29",
        "@wdio/cli": "^5.10.7",
        "@wdio/local-runner": "^5.10.7",
        "@wdio/mocha-framework": "^5.10.1",
        "@wdio/selenium-standalone-service": "^5.9.3",
        "@wdio/spec-reporter": "^5.9.3",
        "@wdio/sync": "^5.10.1",
        "babel-core": "7.0.0-bridge.0",
        "babel-eslint": "^10.0.2",
        "babel-jest": "^24.8.0",
        
...

        "eslint": "^5.16.0",
        "eslint-plugin-jest": "^22.6.4",
        "eslint-plugin-vue": "^5.2.2",
        "jest": "^24.8.0",
        "jest-serializer-vue": "^2.0.2",
        "jest-transform-stub": "^2.0.0",
        "jest-watch-typeahead": "^0.3.1",

...

        "vue-jest": "^3.0.4",
        "vue-template-compiler": "^2.6.10",

...
    },

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. EDIT: I was able to reproduce the problem using this method – see the following comment.

Hope this helps.

I have babel-core@7.0.0-bridge.0 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

✅ 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

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.

None of this worked for me, i am using vuejs

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™. 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 😃

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.

Yeah, you should avoid using Jest in vue cli application. I just replaced vue cli with vue-ssr render and Jest tests work fine now. This issue isn’t solved yet…

Steps vue create foobar

  • Added Unit tests
  • Selected Jest
  • Dedicated config files

npm install npm run test:unit

Error SyntaxError: Unexpected token import

System Windows 10 Vue-Cli 3.0.0

I did a full clean as proposed by @joebartels above, and I also updated (through the UI) to RC3, but to no avail. Same errors.

It seems to appear only in my tests involving vuex.

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.

babel-jest is a transform 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.

You can learn more about how jest works by reading its documentation.

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, making sure that babel-jest is on ^23.6.0 fixes the issue. I know the op maybe didn’t update the deps manually - but maybe something funky happened somehow.

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

Just install babel-core@7.0.0-bridge.0, because babel-jest not fully supports babel@7, as far as I know.

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"
    ]
  }

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.

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.

@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…

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

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 babel-core@7.0.0-bridge.0. 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

Does anybody know how to make this work if you don’t use babel in your vue cli project (only typescript)?

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/']
}

@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.

NODE_ENV=development in my .bashrc

That’s a pretty bad idea.

The source of the problem is very hard to pin down, unfortunately, and it’s frustrating for us as well. It started in early releases for some people, and can have multiple causes/reasons, some not even really solvable by us (i.e importing a npm package that contains es6 exports - requires manual inclusion into babel-jest compilation).

We also fixed a few things that could cause it (i.e. missing babel-core bridge version) at a certain point in time, but unfortunately it seems that it still happens for some people even with latest versions, but I’m not even sure about that right now.

Because identifying the issue is made harder with people that do use vue-cli 3 but don’t share actual (recent) repositories that demonstrate the issue, or at least give specific info about environment, versions theory are on and so forth. Which would help us replicate the problem for those scenarios. “have the same problem” doesn’t do that - it just makes the issue one comment longer and harder to follow.

It is also made harder by people that use all sorts of setups that are not vue cli 3 projects, but chime in with solutions that can’t apply to vue-cli 3, derailing the conversation.

I know all of these people mean well and don’t blame them, but it doesn’t help, unfortunetely.

I also understand that it may seem like we abandoned this issue, but even though we are following the conversation, I’m simply not able to replicate it with recent versions, so I’m left to look at the “me too” comments rolling in, hoping one of the comments gives us something to work with.

That’s why at i attempted to slim down the comment history, hiding outdated or irrelevant replies, as part of an attempt to get back to the core issue we are discussing here.

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"

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 babel-core@7.0.0-bridge.0. 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

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",

@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.

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 notifications@github.com 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.

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 relies on jest and babel-jest 23.*

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.

And to other people following, if you have something else in your transformIgnorePatterns, e.g. the storybook’s "/node_modules/(?!(@storybook/.*\\.vue$))" you can’t just add another line to the array, you must join them in the same regex.

I was just debugging this problem and came to a solution that may help some. The repository I was having the issue with was converted to a Vue cli 3-based project and in that process our jest:update script was still pointing directly to jest and not running through the vue-cli-service.

Updating that from jest -u to vue-cli-service test:unit -u and clearing the cache one final time resolved the issue for me.

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.

@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 !

It’s works for me with this line:

transform: {
'^.+\\.(js|jsx)?$': '<rootDir>/node_modules/babel-jest'
}

I don’t like this solution. Any idea why jest does not find babel-jest?

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.

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

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';

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)'
],

Maybe it helps someone. Took me forever to think about lodash-es being the culprit.


And about this happening with a fresh project: I haven’t been able to reproduce it in any way, unfortunately.

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:

npm i -D @vue/babel-preset-app

My babelrc is simply:

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

I am using nuxt 2, that is not configured to use babelrc (default behavior), so YMMV… but this change above should make testing work fine. Some other things that might apply:

in jest.config.js this may be a nuxt thing? just allows for aliased imports (import foo from '@/components/foo'):

moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
},

And other jest v28 stuff: You’d need jest-environment-jsdom, and @vue/vue2-jest and possible others listed below.

testEnvironment: 'jsdom',
transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.vue$': '@vue/vue2-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
  },

I spent a considerable amount of time trying various combinations of configuration. I finally discovered that for vue-cli v3.11 you must include babel-core@7.0.0-bridge.0. 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! @sirlancelot

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

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.

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 notifications@github.com 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.

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

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.

And to follow up on why that’s happening:

By default jest ignores node_modules and won’t transpile anything inside; so any modules that you source untranspiled would break.

When you add them to transformIgnorePatterns it’s a common pattern to use the forward lookahead regex 🙄, e.g. 'node_modules/(?!(vuetify)/)' which means "ignore everything that has node_modules/ unless it’s followed by vuetify. Having this ignore overrides the default. Now, if you have two or mode modules you need to transpile like this you have to add them to the same first regex because otherwise it will ignore the other modules on the first attempt.

@LinusBorg ok, I created a repo here - https://github.com/chriszrc/vue-cli-jest-test-errors

The commits split out the actions I took, so if you want to see the errors, you can checkout a specific commit if you want. I did the following:

  1. cli create
  2. add bootstrap vue - tests now fail
  3. make jest config modifications, tests now pass

In order to make the tests pass, I had to make the additions seen here:

https://github.com/chriszrc/vue-cli-jest-test-errors/commit/885362d57908103d7b2f8016acbadc7041b75f93#diff-8cc2c6c811a2cb6959ec026bf6d37f58

It worked for me:

https://jestjs.io/docs/en/webpack#mocking-css-modules

moduleNameMapper: {
  '^@/(.*)$': '<rootDir>/src/$1',
  '^src/(.*)$': '<rootDir>/src/$1',
  '\\.(css)$': 'identity-obj-proxy', // add this
},

Well, @Katolus doesn’t seem to be using vuue CLI 3, he seems to be using react, so his comment is likely not relevant to the problem.

@igasparetto The issue you linked to is also not really relevant since we know jest doesn’t support import on its own, which is why we have configured babel-jest and @vue/babel-preset-app to transpile them to commonjs for unit tests.

The question is why that doesn’t work for some people only

After changing jest from 21.2.1 => 23.6.0, similar issue. Switching from .babelrc configurations into babel.config.js fixed the issue.

.babelrc

{
    "presets": [
        "@babel/env",
        "@babel/react"
    ],
    "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", { "loose": false }]
    ]
}

babel.config.js

module.exports = {
    'presets': [
        '@babel/env',
        '@babel/react',
    ],
    'plugins': [
        ['@babel/plugin-proposal-decorators', {'legacy': true}],
        ['@babel/plugin-proposal-class-properties', {'loose': false}],
    ],
};

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"]
    }
  }
}

(much of my configuration was generated from shakacode/react_on_rails

@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.

Lol, I think I tried every solution proposed here. None worked, even @komali2 's

@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

@marlonbarcarol Yes, I’ve done this.

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.

@wangzhanpeng may be on to something

This didn’t work in my project, created with 3.0.1:

transform: {
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
  },

this works:

  transform:  {
    '^.+\\.vue$': 'vue-jest',
    '^.+\\.jsx?$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
  },

The order of this array can break transforms, it seems.

However, I wasn’t able to replicate this with a fresh project created with vue-cli 3.0.1 just now.

This is all pretty weird…

@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?