Vue-jest: vue + jest + typescript: Unexpected token import

Created on 6 Dec 2018  ยท  12Comments  ยท  Source: vuejs/vue-jest

Hi all, I have a Typescript file which imports a Vue file. It seems vue-jest doesn't like this?

/path-to-my-project/Autocomplete/Autocomplete.vue:14
import ItemTemplate from './_autocomplete_item.vue';
^^^^^^

SyntaxError: Unexpected token import

> 1 | import Autocomplete from './Autocomplete/Autocomplete.vue';
    | ^

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (path-to-my-project/base.ts:1:1)

You'll note that it's able to find Autocomplete.vue, but is unable to parse the import _within_ Autocomplete.vue.

Here is my jest config; Am I doing something obviously wrong here?

  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.vue$": "vue-jest"
    },
    "testRegex": "(\\./test/javascript/.*|\\.(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "vue",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
need repro

Most helpful comment

I finally found a way to make it work ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰ by adding these lines to the jet.config.js:

  preset: 'ts-jest/presets/js-with-ts',
  transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],

Thanks to: https://stackoverflow.com/questions/53397773/node-modules-not-being-parsed-correctly-for-tests/53414070#53414070

I also had to add "allowJs": true, to my tsconfig.json

I hope it can help you out!

All 12 comments

I'm seeing a similar issue, with pretty much the same setup (latest Vue & TypeScript), but haven't been able to figure out a solution or workaround so far.

The error is slightly different for me though, and almost looks like it's having trouble processing transpiled/transformed code?

/Users/dids/<project>/src/components/JSONEditorComponent.vue:2
    import "regenerator-runtime/runtime";
    ^^^^^^

    SyntaxError: Unexpected token import

      1 | import { shallowMount } from '@vue/test-utils'
    > 2 | import JSONEditorComponent from '../JSONEditorComponent.vue'
        | ^
      3 |
      4 | describe('JSONEditorComponent.vue', () => {
      5 |   test('renders props.msg when passed', () => {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/components/__tests__/JSONEditorComponent.spec.ts:2:1)

@mattgrande Is your TypeScript config set to target esnext or es2015? I've tried both, but iirc Vue CLI defaults to esnext, in case that makes a difference.

Good thought on that, no luck though, unfortunately. I'm currently set to es5, and tried a few others, but same issue each time.

Thanks for confirming the issue, @Dids! Glad to hear I'm not the only one with this problem.

@rumanbsl - It looks like there's still some discussion going on with it; I will check it out once the CI is passing :)

Any news on this issue ? I also get this error ๐Ÿ‘Ž

Here is a repro of the issue:
https://github.com/francoismassart/vuejs-vue-jest-ts-unexpected-token-repro

I made this using vue-cli, then using a component from bootstrap-vue and using mount instead of shallowMount.

I get the following error while trying to run the unit tests

> vue-cli-service test:unit

 FAIL  tests/unit/example.spec.ts
  โ— Test suite failed to run

    /Users/francois/vuejs-vue-jest-ts-unexpected-token-repro/node_modules/bootstrap-vue/es/components/table/table.js:3
    import startCase from 'lodash.startcase';
           ^^^^^^^^^

    SyntaxError: Unexpected identifier

       7 |
       8 | <script lang="ts">
    >  9 | import bTable from 'bootstrap-vue/es/components/table/table';
         | ^
      10 | import Vue from 'vue';
      11 |
      12 | const demoItems = [

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at src/components/HelloWorld.vue:9:1
      at Object.<anonymous> (src/components/HelloWorld.vue:56:3)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        5.723s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test:unit: `vue-cli-service test:unit`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] 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/francois/.npm/_logs/2019-02-08T08_13_10_343Z-debug.log

@francoismassart Jest doesn't transform files in node_modules by default. You need to update your jest.config.js file to transform bootstrap-vue and compile js files with babel-jest:

// jest.config.js
module.exports = {
  transform: {
    // ..
    '^.+\\.jsx?$': 'babel-jest'
  },
  transformIgnorePatterns: ["/node_modules/(?!(bootstrap-vue)/)"],
  // ..
}

I finally found a way to make it work ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰ by adding these lines to the jet.config.js:

  preset: 'ts-jest/presets/js-with-ts',
  transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],

Thanks to: https://stackoverflow.com/questions/53397773/node-modules-not-being-parsed-correctly-for-tests/53414070#53414070

I also had to add "allowJs": true, to my tsconfig.json

I hope it can help you out!

Thank you for your help @eddyerburgh !
Your solution works as well ๐Ÿ‘

Do you know what's the best solution between:

  preset: 'ts-jest/presets/js-with-ts',
  transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],

-OR-

  transform: {
    // ..
    '^.+\\.jsx?$': 'babel-jest'
  },
  transformIgnorePatterns: ["/node_modules/(?!(bootstrap-vue)/)"],
  // ..
}

Maybe adding '^.+\\.jsx?$': 'babel-jest' is lighter than applying all the changes defined inside the preset... ?

The original problem doesn't reference a node_module though. We have the same problem with a pure typescript vue component.

   Details:

    /Users/me/Sites/shopping-dev/vagrant/discovery-client/assets/js/components/watchlist/WatchlistTileWrapper.vue:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _typeof from "@babel/runtime/helpers/typeof";
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      1 | import { createLocalVue, mount } from '@vue/test-utils';
      2 | import Vuex from 'vuex';
    > 3 | import WatchlistTileWrapper from './WatchlistTileWrapper.vue';
        | ^
      4 | import { registerWatchlistComponents } from '../registerWatchlist';
      5 | import { watchlistTileMock } from '../../tests/components/watchlistTileMocks';
      6 |

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (assets/js/components/watchlist/WatchlistTileWrapper.spec.ts:3:1)

Our transform config looks like this:

transform: {
        '^.+\\.vue$': 'jest-vue-preprocessor',
        '^.+\\.(css|scss|less)$': 'jest-css-modules',
        //'.+\\.(css|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
        '^.+\\.js$': 'babel-jest',
        '^.+\\.tsx?$': 'ts-jest',
    },

    // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
    transformIgnorePatterns: [
        '/node_modules/',
        '/vendor/',
    ],

+1

@francoismassart Jest doesn't transform files in node_modules by default. You need to update your jest.config.js file to transform bootstrap-vue and compile js files with babel-jest:

// jest.config.js
module.exports = {
  transform: {
    // ..
    '^.+\\.jsx?$': 'babel-jest'
  },
  transformIgnorePatterns: ["/node_modules/(?!(bootstrap-vue)/)"],
  // ..
}

Good lord. Been banging my head against this for HOURS trying to get ts-jest to work.

This solved it, thanks!

@francoismassart this solved for mee too!
wheen need to transform two packages (in my case: vue-material design icons and vue spinner) I updated jest.config.js like this:

transformIgnorePatterns: ['/node_modules/(?!(vue-material-design-icons)|(vue-spinner))']

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chenxeed picture chenxeed  ยท  5Comments

Loremaster picture Loremaster  ยท  7Comments

aantipov picture aantipov  ยท  8Comments

xereda picture xereda  ยท  4Comments

nogic1008 picture nogic1008  ยท  4Comments