Fix Cypress “Invalid or unexpected token” errors in parallel runs

David Cai
2 min readFeb 23, 2021


Cypress test has been working very well for my project. But lately I started to get the mysterious “Invalid or unexpected token” errors after I changed my CI pipeline to use Cypress’ parallel testing.

The error message “originated from your test code” made me think if there is any syntax error in my test specs. But if so, the Cypress test should have failed every time, rather than intermittently.

Invalid or unexpected token error

My Cypress test specs are coded in TypeScript. This led me to speculate if compiling TypeScript code in Cypress’ parallel mode could cause overwriting in files among Cypress testers. A bit of google search also confirmed my theory.

One solution that worked for me is to isolate test files in their test runs, so test code will not get overwritten by other testers.

In plugins/index.js, I have this code to append unique IDs to filenames before Webpack processes test files:

// plugins/index.jsconst webpackPreprocessor = require("@cypress/webpack-batteries-included-preprocessor");const { v4: uuid } = require("uuid");const filePreprocessor = webpackPreprocessor({ typescript: "typescript" });module.exports = on => {  const id = uuid();  on("file:preprocessor", file => {    file.outputPath = file.outputPath.replace(/^(.*\/)(.*?)(\..*)$/, `$1$2.${id}$3`);    return filePreprocessor(file);  });};

This is the key line:

file.outputPath.replace(/^(.*\/)(.*?)(\..*)$/, `$1$2.${id}$3`)

If a file’s path is “cypress/integration/abc.spec.ts”, the path will be replaced with “cypress/integration/abc.<uuid>.spec.ts”. <uuid> is unique among each tester run.

I need to install “@cypress/webpack-batteries-included-preprocessor” and “@cypress/webpack-preprocessor”, so my plugin file can access webpack and its file preprocessors.

npm install -D @cypress/webpack-preprocessor @cypress/webpack-batteries-included-preprocessor

With this fix, I haven’t encountered any “Invalid or unexpected token” error. Hope this tip helps.



David Cai

Gamer, hiker, reader, and programmer