Run jest got "Unexpected string" at ScriptTransformer._transformAndBuildScript

Had the same issue.

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

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

    SyntaxError: Unexpected string

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

Tried the answer above.This article solved my problem.

Solution:

  1. npm uninstall "@vue/cli-plugin-unit-jest"
  2. deleted tests folder with all content
  3. deleted jest.config.js file
  4. vue add @vue/cli-plugin-unit-jest
  5. for VS Code use the next launch.json

{
  "version": "0.2.0",
  "configurations": [            
    {
      "name": "vscode-jest-tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect-brk",
        "./node_modules/@vue/cli-service/bin/vue-cli-service.js",
        "test:unit",
        "--runInBand"
      ],
      "cwd": "${workspaceFolder}",
      "protocol": "inspector",
      "disableOptimisticBPs": true,
      "console": "integratedTerminal",    
      "internalConsoleOptions": "neverOpen",
      "outFiles": [ "${workspaceFolder}/src/**/*.js"],
      "port": 9229
    },
  ]
}

After struggling for a few days. Finally, I got the solution to run jest in debug mode for VueJs application.

After debuging into vue-cli-service and in turn @vue/cli-plugin-unit-jest, I found the following code before it spawns the jest process:

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

Solution

So the solution is very simple.

Just add these two environment variables before running the jest command. The following commands will start jest in debug mode:

export VUE_CLI_BABEL_TARGET_NODE=true
export VUE_CLI_BABEL_TRANSPILE_MODULES=true
./node_modules/jest/bin/jest.js --clearCache
node --inspect-brk ./node_modules/jest/bin/jest.js -i

Notes

  • Make sure DON'T add ".babel.rc", this will mass up VueJS babel.

  • And often, you will need to run jest with the --clearCache option. Otherwise, the stale generated file will also mess up.

  • The jest option -i is also important. Otherwise, the test will be running in a separate process which will not be in debug mode.

Tags:

Vue.Js

Jestjs