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
- fix unit test setup add jest transform (see https://github.com/vuejs/vue-cli/issues/1584) — committed to ConnorStroomberg/molgenis-app-biobank-explorer by ConnorStroomberg 6 years ago
- Can not run jest still... https://github.com/vuejs/vue-cli/issues/1584 Fuck... — committed to hongshu-corp/quokka-admin by jerecui 6 years ago
- store.test.js: add import statement for debugging https://github.com/vuejs/vue-cli/issues/1584 — committed to NYULibraries/dlts-enm-search-application by da70 5 years ago
- package.json: use "jest" for "test:unit" instead of "vue-cli-service test:unit" to work around https://github.com/vuejs/vue-cli/issues/1584 — committed to NYULibraries/dlts-enm-search-application by da70 5 years ago
- package.json: use "jest" for "test:unit" instead of "vue-cli-service test:unit" to work around https://github.com/vuejs/vue-cli/issues/1584 — committed to NYULibraries/dlts-enm-search-application by da70 5 years ago
- package.json: set "transform" ordering to match that made by new Vue CLI 3 created project [+] There is some evidence that the order matters: https://github.com/vuejs/vue-cli/issues/1584#issuecommen... — committed to NYULibraries/dlts-enm-search-application by da70 5 years ago
Adding
'^.+\\.js$': 'babel-jest'
was not enough for me. Tests run only on empty cache once and started throwingUnexpected token
errors on change. As mentioned here I also had to addtransformIgnorePatterns ['<rootDir>/node_modules/']
to myjest.config.js
Full
jest.config.js
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
: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
ornpm install --save-dev @babel/core @babel/preset-env
Create a new file called
babel.config.js
in the same directory aspackage.json
. Put the following content in it: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 torc.3
from one of the betas (beta.16 I think). I did arm -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 allrc.3
@vue/*
packages but for some reason it no longer errored.I can reproduce this on a fresh project if I update
babel-jest
:Output:
Note that simply downgrading (
npm install --save-dev babel-jest@23
) will not fix the problem on its own. I had to removenode_modules
andpackage-lock.json
and clear the jest cache, before the tests would run again:I was able to fix this issue by adding the following to the jest.config.js transform section:
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 withvue-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’ 😄@samayo http://lmgtfy.com/?q=babel-jest
Adding .babelrc into my project root directory fixes the import problem.
My
.babelrc
looks like: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
npx jest --clearCache
works for me.For me the following did the trick:
If that doesn’t work, delete
node_modules
andpackage-lock.json
, and then runnpm 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 includebabel-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 runnpx jest --clearCache
. After that, Jest should start usingbabel-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#L58Would 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 onimport
when runningvue-cli-service test:unit
: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:
vue-cli-service test:unit
using--no-cache
.node_modules/
from scratch.babel-jest
to<rootDir>/node_modules/babel-jest
.babel.config.js
change from this earlier comment<rootDir>/babel.config.js
totests/unit/
and then latertests/unit/store/
(where failing test file store.test.js was)".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
from jest transform configurationI 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"
todevDependencies
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:The jest configuration (in
package.json
):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 withdevDependencies
set to above and refreshingnode_modules
should reproduce the problem. I tested this in my project and was able to recreate theimport
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.
solved my issue by making babel.config.js to look like this:
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:
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.config.js:
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:
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:My
.babelrc
looks like:HTH 😃
Here’s the
babel.config.js
that’s working for me: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
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 notyarn 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#L13env VUE_CLI_BABEL_TARGET_NODE=true VUE_CLI_BABEL_TRANSPILE_MODULES=true yarn jest
is working for me. Still, must runyarn 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
, becausebabel-jest
not fully supportsbabel@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:
package.json:
I’ve solved the issue.
Make sure you have these exact versions of the following packages installed:
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:I also ran
jest --clearCache
afterwards, and naturally addedbabel-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:
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
babel.config.js
jest.config.js
@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.
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:
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!Figured it out via a new project via vue cli 3.10.0. If you upgrade babel-jest to 24.x.x this happens:
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.
@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:
– R. Mark Volkmann Object Computing, Inc.
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.
@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 tojest
and not running through thevue-cli-service
.Updating that from
jest -u
tovue-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:
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:
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, notjest
directly, right?I “fixed” this problem for my project by adding the
.vue
extension to the imports in tests. Hope this helps.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 withimport
andexport
statements into my tests, which of course broke.When I added the following to my jest config, it worked:
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:
My babelrc is simply:
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'
):And other jest v28 stuff: You’d need jest-environment-jsdom, and @vue/vue2-jest and possible others listed below.
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:Attempting to debug the test with VSCode with the following configuration mentioned in various articles…
I run into the following error:
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:
– 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 hasnode_modules/
unless it’s followed byvuetify
. 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:
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
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 intobabel.config.js
fixed the issue..babelrc
babel.config.js
Following what @naveensenapathi did I found the minimum configuration change that worked for me (not using vue-cli, but still ran into this issue)
Thank you @naveensenapathi!
Complete configuration
package.json
.babelrc
(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:
this works:
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?