Search code examples
typescriptjestjsbabeljspuppeteernest

JEST - SyntaxError: Unexpected token 'export' with uuid library


I used to solve similar errors while I was using Jest with only JavaScript, but currently I'm not able to do so with Typescript.

All my tests were running fine until I installed Puppeteer which requires @types/jest-environment-puppeteer, @types/puppeteer and @types/expect-puppeteer.

After installing them, puppeteer tests are running perfectly, but other tests started to fail with below error.

  D:\...\api\node_modules\uuid\dist\esm-browser\index.js:1    
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^  

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)   
      at Object.require (../node_modules/@nestjs/common/decorators/core/injectable.decorator.js:4:16)

WHAT I DID?

allowJs: true on tsconfig.json and set the transformIgnorePatterns on jest configs. So that jest can compile files from node_modules/ After that this error stopped but test failed for another strange reason. And worse is that test start time have increased too much.

So I left allowJs as in original setup and updated jest config from

"transform": {
   "^.+\\.(t|j)s$": "ts-jest"
}

to

"transform": {
   "^.+\\.(t)s$": "ts-jest"
}

So currently ts-jest doesnt compile js files. But I think I am not able to make babel pick the transformation for js files. These are my jest configs:

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t)s$": "ts-jest",
    "^.+\\.(js|jsx)$": "babel-jest"
  },
  "transformIgnorePatterns": ["<rootDir>/node_modules/.+.(js|jsx)$"]
}

Solution

  • Thanks to this reply: https://stackoverflow.com/a/54117206/15741905

    I started googling for similar fixes and ended up here: https://github.com/uuidjs/uuid/issues/451

    And this solved my problem: https://github.com/uuidjs/uuid/issues/451#issuecomment-1112328417

    // jest.config.js
    {
    //................
      moduleNameMapper: {
        // Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
        "uuid": require.resolve('uuid'),
      }
    }
    

    Tough I would still be happy if there is solution to this by using jest-babel.

    Because I had to carry jest configs from package.json to a seperate .js file.

    Edit: According to this github issue compatibility issue has been solved with the latest release of the uuid library.