New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default unit tests are failing #1879

Open
maxpou opened this Issue Jul 17, 2018 · 31 comments

Comments

Projects
None yet
@maxpou
Copy link

maxpou commented Jul 17, 2018

Version

3.0.0-rc.5

Reproduction link

https://codesandbox.io/s/vue

Steps to reproduce

vue create vue-jest
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, Linter, Unit
? Pick a linter / formatter config: Basic
? Pick additional lint features: Lint on save
? 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

duplicate HelloWorld.spec.js (i.e. Users.spec.js)

What is expected?

test should pass.

What is actually happening?

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

    /lab/vue-jest/tests/unit/Users.spec.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "core-js/modules/es6.array.iterator";
                                                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected string

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

In jest.config.js I added cache: false to solve the error.
Other information:

  • yarn v 1.6.0
  • node v10.1.0
  • macos High Sierra
@k-chromatic

This comment has been minimized.

Copy link

k-chromatic commented Jul 17, 2018

I am getting a similar error as well, expect mine says SyntaxError: Unexpected token import

This may be related to this issue:

#1524 (comment)

@yyx990803

This comment has been minimized.

Copy link
Member

yyx990803 commented Jul 18, 2018

Can't reproduce with Yarn 1.7 & Node 10.3.0 on macOS. Try upgrading Yarn?

@maxpou

This comment has been minimized.

Copy link

maxpou commented Jul 18, 2018

I'm now with yarn 1.7. Problem persist. Same output.
I tried without yarn: rm -rf node_modules && npm i && npm run test:unit. Idem: same output. (using npm v 6.1.0)

@k-chromatic

This comment has been minimized.

Copy link

k-chromatic commented Jul 18, 2018

The problem seems to be with the environment variables VUE_CLI_BABEL_TARGET_NODE and VUE_CLI_BABEL_TRANSPILE_MODULES. If they are set to true, the issue goes away.

Jianwu Chen on stackoverflow.com found this solution:

https://stackoverflow.com/questions/51365250/run-jest-got-unexpected-string-at-scripttransformer-transformandbuildscript

@yyx990803

This comment has been minimized.

Copy link
Member

yyx990803 commented Jul 18, 2018

Are you running jest directly? That's not supposed to work. You must run it via vue-cli-service test:unit.

@yyx990803

This comment has been minimized.

Copy link
Member

yyx990803 commented Jul 18, 2018

@javacoldbrew FYI just landed cd88cfa which allows you to debug vue-cli-service test:unit via Node inspector.

@k-chromatic

This comment has been minimized.

Copy link

k-chromatic commented Jul 19, 2018

@yyx990803 I feel silly, I am pretty sure that was my problem. I was running the tests through IntelliJ's Jest runner which just calls jest directly, which would sometimes work.

I will double check and get back to you tomorrow and see if I still get the error when using yarn run test:unit.

Anyways, thank you for all your help!

@maxpou

This comment has been minimized.

Copy link

maxpou commented Jul 19, 2018

@yyx990803 I'm using the yarn run test:unit / npm run test:unit

@mghignet

This comment has been minimized.

Copy link

mghignet commented Jul 23, 2018

Hi,

What version of babel-jest are you using?
I had the same issue with version 23.0.1 and I solved it using version 23.4.0.
I made a mistake when trying to fix versions in my package.json which led me to use the wrong one.
If that can help... 👍

@erwin16

This comment has been minimized.

Copy link

erwin16 commented Jul 28, 2018

running default unit tests is failing ....

upgrading to 23.4.0 raises a lot of wrnings;;;

	 yarn upgrade babel-jest@23.4.0
	yarn upgrade v1.9.2
	[1/4] 🔍  Resolving packages...
	[2/4] 🚚  Fetching packages...
	[3/4] 🔗  Linking dependencies...
	warning "@vue/cli-plugin-babel > babel-loader@8.0.0-beta.4" has unmet peer dependency "webpack@>=2".
	warning "@vue/cli-plugin-eslint > eslint-loader@2.1.0" has unmet peer dependency "webpack@>=2.0.0 <5.0.0".
	warning "@vue/cli-plugin-pwa > workbox-webpack-plugin@3.4.1" has unmet peer dependency "webpack@^2.0.0 || ^3.0.0 || ^4.0.0".
	warning "@vue/eslint-config-prettier > eslint-config-prettier@2.9.0" has unmet peer dependency "eslint@>=3.14.1".
	warning " > babel-core@7.0.0-bridge.0" has unmet peer dependency "@babel/core@^7.0.0-0".
	warning " > sass-loader@7.0.3" has unmet peer dependency "webpack@^3.0.0 || ^4.0.0".
@ntsim

This comment has been minimized.

Copy link

ntsim commented Aug 1, 2018

Updating jest to 23.4.2 seems to cause these failing tests for me. There appears to be some dependencies that don't play well together. I could not quite track down the true source. Even after trawling through Jest's recent changes, it does not look like anything specifically could cause this.

Anyone else running into this issue, you should be able to workaround it by installing jest-cli and pinning it exactly to 23.4.1.

@ChristianAEDev

This comment has been minimized.

Copy link

ChristianAEDev commented Aug 2, 2018

I believe I solved this problem by adding the following to the jest.config.js:

transformIgnorePatterns: [
    "node_modules/(?!(babel-jest|jest-vue-preprocessor)/)"
  ]

I sadly have to say "I believe...", because since I added this option to a newly created Vue project (using Vue CLI v3.0.0-rc.10) it suddenly also works for another project, where I didn't add this option.

I am therefore not exactly sure what solved the issue and I am not able to reproduce it anymore.
But I wanted to leave this here for others to try out.

The following links helped me to find this solution:

@simonjohansson

This comment has been minimized.

Copy link

simonjohansson commented Aug 2, 2018

@ChristianAEDev

Thanks, this solved it for me, until I change a test file. After running ./node_modules/jest/bin/jest.js --clearCache the tests are working again.

$ cat tests/unit/HelloWorld.spec.ts
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message';
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg },
    });
    expect(wrapper.text()).toMatch(msg);
  });
});

$ npm run test:unit
> frontend@0.1.0 test:unit /Users/sjo4473/src/simonjohansson/quiz/frontend
> vue-cli-service test:unit

 PASS  tests/unit/HelloWorld.spec.ts
  HelloWorld.vue
    ✓ renders props.msg when passed (26ms)

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

$ vim tests/unit/HelloWorld.spec.ts
$ cat tests/unit/HelloWorld.spec.ts
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message';
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg },
    });
    expect(wrapper.text()).toMatch(msg);
  });

  it('blurgh', () => {
    expect(true).toBeTruthy();
  });
});

$ npm run test:unit
> frontend@0.1.0 test:unit /Users/sjo4473/src/simonjohansson/quiz/frontend
> vue-cli-service test:unit

 FAIL  tests/unit/HelloWorld.spec.ts
  ● 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/sjo4473/src/simonjohansson/quiz/frontend/tests/unit/HelloWorld.spec.ts:3
    import "core-js/modules/es6.array.iterator";
    ^^^^^^

    SyntaxError: Unexpected token import

      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.079s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! frontend@0.1.0 test:unit: `vue-cli-service test:unit`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the frontend@0.1.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/sjo4473/.npm/_logs/2018-08-02T15_05_54_261Z-debug.log

$ ./node_modules/jest/bin/jest.js --clearCache
Cleared /var/folders/2z/g6z_y_4d6hn03vfx9k9gwfp8bxwvxb/T/jest_6mf3xn

$ npm run test:unit
> frontend@0.1.0 test:unit /Users/sjo4473/src/simonjohansson/quiz/frontend
> vue-cli-service test:unit

 PASS  tests/unit/HelloWorld.spec.ts
  HelloWorld.vue
    ✓ renders props.msg when passed (23ms)
    ✓ blurgh (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.163s
Ran all test suites.
@ebertti

This comment has been minimized.

Copy link

ebertti commented Aug 4, 2018

This is not a perfect soluction, but I think this can be used temporarily

  transformIgnorePatterns: [
    '/node_modules/.*',
  ],

and creating a .env.test on project root dir with this values

VUE_CLI_BABEL_TARGET_NODE=true
VUE_CLI_BABEL_TRANSPILE_MODULES=true

It works great for me running jest directly on Jetbrains IDE test

@yyx990803

This comment has been minimized.

Copy link
Member

yyx990803 commented Aug 7, 2018

For users seeing the same problem: do you have a default NODE_ENV set for your shell?

@mathieumure

This comment has been minimized.

Copy link

mathieumure commented Aug 8, 2018

@yyx990803, I have the same problem and no default NODE_ENV are set in my shell.

@yyx990803

This comment has been minimized.

Copy link
Member

yyx990803 commented Aug 8, 2018

@mathieumure still happening with RC11?

@simonjohansson

This comment has been minimized.

Copy link

simonjohansson commented Aug 9, 2018

I noticed that as soon as I stopped using the jest plugin in Visual Studio Code the issue went away for me.

@mathieumure

This comment has been minimized.

Copy link

mathieumure commented Aug 10, 2018

@yyx990803 stop happening after stopping using jest directly from both my shell and IDE...I miss read the whole thread, my bad 😅 .
But still, I wonder if using vue-cli-service instead of jest will not broke a lot of integration in IDE...

@ntsim

This comment has been minimized.

Copy link

ntsim commented Aug 11, 2018

After spending some time debugging the issue, I think I've come up with a feasible solution. It seems like this comes down to a 'wtf' moment in terms of how NPM's dependency resolution strategy works. The following seems to be the solution for me, but your mileage may vary depending on the specific scenario.

TLDR

You can do either of these things:

  1. Clear down node_modules and remove package-lock.json. Re-run npm install.
  2. Run npm cache verify and re-run npm install.

I personally think doing both is the best option to ensure everything is sound and your package-lock.json is more in-line with Vue CLI when it generates a fresh project.

Long explanation

The intention seems to be that cli-plugin-unit-jest tries to depend on the root level babel-core, which in combination with cli-plugin-babel is usually babel-core@7.0.0-bridge.0. This is normally fine, but for some unlucky people, NPM can incorrectly resolve babel-core@6.26.3 as a nested dependency of the plugin (instead of being at the root level of node_modules). As it's essentially the wrong version, all sorts of weird things probably happen behind the scenes, but the bottom line is that Jest cannot transform the code correctly.

Why does this happen? I'm not 100% sure (I am no expert in the NPM dependency resolution algorithm) but my best guess is that:

  • cli-plugin-unit-jest relies on babel-core@6.26.3 indirectly through one of it's dependencies. I think it is babel-jest in this case, but as it is a peer dependency, it means that babel-core@7.0.0-bridge.0 should theoretically be used.

  • When NPM has to resolve dependencies for babel-jest on the project level e.g. when updating it in my case, the algorithm gets confused and believes babel-core can't be resolved as a peer dependency. I believe this is at least partly due to the NPM cache being corrupted or caching incorrect dependencies in some way. NPM resolves babel-core@6.26.3 as a nested dependency instead and everything breaks.

It seems like the way to resolve this involves ensuring the NPM cache is correct and consistent (i.e. npm cache verify), and/or rebuilding the package-lock.json and node_modules entirely to make sure it resolves everything from scratch again (without any external caching factors).

@Nivani

This comment has been minimized.

Copy link

Nivani commented Aug 17, 2018

I found a workaround based on the one posted by @ebertti and the code of the vue-plugin-unit-test module.

Adding the following at the top of the jest.config.js file fixes the problem:

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

This comment has been minimized.

Copy link

uglow commented Aug 28, 2018

Thanks @ntsim - your solution seems to have worked.

For other people struggling with this problem (which for me looked like this:

$npm run test:unit

> web-common@0.1.0 test:unit /code/monorepo/packages/web-common
> vue-cli-service test:unit

 FAIL  src/components/Header.spec.js
  ● Test suite failed to run

    Plugin 0 specified in "/code/monorepo/packages/web-common/node_modules/@vue/babel-preset-app/index.js" provided an invalid property of "default" (While processing preset: "/code/monorepo/packages/web-common/node_modules/@vue/babel-preset-app/index.js")

      at Plugin.init (../../node_modules/jest-config/node_modules/babel-core/lib/transformation/plugin.js:131:13)
          at Array.map (<anonymous>)
          at Array.map (<anonymous>)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.123s

), I've been using Lerna with sub-packages and that seems to re-produce the error every time I run lerna bootstrap --hoist. As soon as I do a straight npm install in the sub-package (after having applied your solution), it works again.

Update: It also works if I use lerna bootstrap without the --hoist option.

@macdaddyaz

This comment has been minimized.

Copy link

macdaddyaz commented Oct 24, 2018

I found a workaround based on the one posted by @ebertti and the code of the vue-plugin-unit-test module.

Adding the following at the top of the jest.config.js file fixes the problem:

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

Personally, I found this solution proposed by @Nivani to be sufficient without any other changes (in a project generated with CLI 3.0.5). I also found that if I don't want to "pollute" the Jest config file, I can just set the env vars in the IDE's run configuration.

Another option is to create a separate config file for the IDE to use that looks like this:

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

const config = require( './jest.config');
module.exports = config;

I called it jetbrains-jest.config.js and then selected it as the "Configuration file" in the Jest run configuration. That way, Vue CLI can be Vue CLI, and WebStorm can be WebStorm.

@Aaron-Pool

This comment has been minimized.

Copy link

Aaron-Pool commented Oct 30, 2018

The simple

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

addition at the top of my jest config file seems to have fixed things for me as well.

@LinusBorg

This comment has been minimized.

Copy link
Member

LinusBorg commented Oct 31, 2018

Weird. vue-cli-service test:unit sets these variables for you before running jest:

https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-plugin-unit-jest/index.js#L13-L15

The question then would be why they are lost for some people.

@cars10

This comment has been minimized.

Copy link

cars10 commented Nov 1, 2018

I also faced that issue. What helped me was:

  • setting babel-core to ~7.0.0-bridge.0 in package.json
  • running npx jest --clearCache

After that everything worked again.

@leumashz

This comment has been minimized.

Copy link

leumashz commented Nov 13, 2018

@cars10 Solution worked for me.

@jackkoppa

This comment has been minimized.

Copy link

jackkoppa commented Nov 13, 2018

@cars10, also worked for me. After installing babel-core at ~7.0.0-bridge.0, we're using

"test:unit": "jest --clearCache && vue-cli-service test:unit",

right now, to avoid the errors whenever we test. Obviously, that's less than ideal if our tests start to get larger. And we're also not super comfortable about still requiring babel-core when we should likely only be using

"@babel/core": "^7.1.5",

So I'll keep an eye on this

@dasDaniel

This comment has been minimized.

Copy link

dasDaniel commented Dec 17, 2018

I found a workaround based on the one posted by @ebertti and the code of the vue-plugin-unit-test module.

Adding the following at the top of the jest.config.js file fixes the problem:

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

this is, IMHO, way faster than waiting for all tests to finish, when you're only working on one file.

Though it should be noted that it can also be done using npm run test:unit myComponent. or vue-cli-service test:unit "myComponent" (to run myComponent.spec.js) I'm sure it's documented somewhere, but I haven't come cross it and stopped looking. However you can't (seem to) pass more than one argument, so for example, you may either clear a snaptshot or run a specific test, but you cannot clear a snapshot on a specific test.

maybe this:

All Jest command line options are also supported.

@Himujjal

This comment has been minimized.

Copy link

Himujjal commented Jan 16, 2019

I also faced that issue. What helped me was:

* setting `babel-core` to `~7.0.0-bridge.0` in `package.json`

* running `npx jest --clearCache`

After that everything worked again.

This worked like a charm! Thanks

@plondon

This comment has been minimized.

Copy link

plondon commented Jan 16, 2019

@cars10 you just saved my life, if you accept bitcoin ill send you some 💸

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment