2

I am using Jest for testing my Angular application but am getting the following errors:

● 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:

    /home/cxo/Projects/git/sparta/clients/vaph/node_modules/@ckeditor/ckeditor5-watchdog/src/editorwatchdog.js:12
    import { throttle, cloneDeepWith, isElement } from 'lodash-es';
           ^

    SyntaxError: Unexpected token {

      at Runtime.createScriptFromCode (../../../node_modules/jest-runtime/build/index.js:1258:14)
      at ../../../node_modules/@ckeditor/ckeditor5-angular/bundles/ckeditor-ckeditor5-angular.umd.js:2:85
      at Object.<anonymous> (../../../node_modules/@ckeditor/ckeditor5-angular/bundles/ckeditor-ckeditor5-angular.umd.js:5:2)

Am also using https://nx.dev/angular.

This is my jest config:

module.exports = {
  testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
  transform: {
    '^.+\\.(ts|js|html)$': 'ts-jest',
  },
  resolver: '@nrwl/jest/plugins/resolver',
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageReporters: ['html'],
};

My package.json looks like:

{
  "name": "App-Name",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "nx": "nx",
    "start": "ng serve",

   // SEVERAL ENTRIES ARE OMITTED FOR CLARITY  
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^9.1.12",
    "@angular/cdk": "~9.2.4",
    "@angular/common": "^9.1.12",
    "@angular/compiler": "^9.1.12",
    "@angular/core": "^9.1.12",
    "@angular/forms": "^9.1.12",
    "@angular/localize": "~9.1.12",
    "@angular/material": "~9.2.4",
    "@angular/material-moment-adapter": "^9.2.4",
    "@angular/platform-browser": "^9.1.12",
    "@angular/platform-browser-dynamic": "^9.1.12",
    "@angular/router": "^9.1.12",
    "@angular/service-worker": "~9.1.12",
    "@auth0/angular-jwt": "^4.1.2",
    "@babel/polyfill": "^7.10.4",
    "@ckeditor/ckeditor5-angular": "^1.2.3",
    "@ckeditor/ckeditor5-build-balloon": "^19.0.0",
    "@ckeditor/ckeditor5-build-balloon-block": "^19.0.0",
    "@ckeditor/ckeditor5-build-classic": "^19.0.0",
    "@ckeditor/ckeditor5-build-decoupled-document": "^19.0.0",
    "@ckeditor/ckeditor5-build-inline": "^19.0.0",
    "@nrwl/angular": "9.5.1",
    "angular-build-info": "^1.0.7",
    "angular-notifier": "^6.0.1",
    "core-js": "^2.5.4",
    "file-saver": "^2.0.2",
    "ng2-file-upload": "^1.4.0",

    // SEVERAL ENTRIES ARE OMITTED FOR CLARITY  

    "secure-ls": "^1.2.6",
    "zone.js": "^0.10.2"
  },
 "devDependencies": {
     "@angular-devkit/build-angular": "^0.901.11",
     "@angular/cli": "^9.1.11",
     "@angular/compiler-cli": "^9.1.12",
     "@angular/language-service": "^9.1.12",
     "@compodoc/compodoc": "^1.1.11",
     "@ngneat/spectator": "^5.12.0",
     "@nrwl/cypress": "9.5.1",
     "@nrwl/jest": "9.5.1",
     "@nrwl/workspace": "9.5.1",
     "@types/crypto-js": "^3.1.47",
     "@types/jest": "25.1.4",
     "@types/node": "~12.12.50",
     "dotenv": "6.2.0",
     "eslint": "6.8.0",
     "jest": "25.2.3",
     "jest-preset-angular": "8.1.2",
     "ng-mocks": "^10.1.1",
     "ng-openapi-gen": "^0.12.1",
     "ts-jest": "25.2.1",
     "ts-node": "~7.0.0",
     "tslint": "~6.0.0",
     "typescript": "~3.8.3"
}
}

tsconfig.json looks like:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2017", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {
      // SEVERAL LINES OMITTED FOR CLARITY
    }
  },
  "exclude": ["node_modules", "tmp"]
  "compilerOptions": {
    "types": ["node", "jest"]
  },
  "include": ["**/*.ts"]
}

This is the tsconfig.lib.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../../dist/out-tsc",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": ["dom", "es2018"]
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": ["src/test-setup.ts", "**/*.spec.ts"]
}

This is tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "../../../dist/out-tsc",
    "module": "commonjs",
    "types": ["jest", "node"]
  },
  "files": ["src/test-setup.ts"],
  "include": ["**/*.spec.ts", "**/*.d.ts"]
}

I have searched the web and debugged, but to no avail. I did what was suggested in this post but to no avail.

In the error message it says that By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

I don't know if I have to install babeljs also.

Eddy Freeman
  • 3,207
  • 6
  • 35
  • 55
  • It looks like you imported this module `ckeditor5-watchdog/src/editorwatchdog.js` which is written in `esm` module so you have to transpile this package as well setup in `webpack.config` file – tmhao2005 Aug 17 '20 at 09:10
  • Have you looked at [the ts-jest presets](https://kulshekhar.github.io/ts-jest/user/config/#jest-preset)? I believe the `preset` does a lot more than specifying the `tranformer` – Aluan Haddad Aug 17 '20 at 09:11
  • @tmhao2005 Webpack versions dating back several years automatically handle ESM dependencies, it is commonly used to create more optimizable libraries. This doesn't mean Webpack will transpile all ES2015+ syntax in the file, only the `import`, `export`, and `import()`. – Aluan Haddad Aug 17 '20 at 09:13
  • Sorry I didn't see he set `ts-jest` instead of using `babel` as default. Can you share us your `tsconfig.json` as well? – tmhao2005 Aug 17 '20 at 09:35
  • @tmhao2005 i have updated the post with the tsconfig.json, tsconfig.lib.json and the tsconfig.spec.json – Eddy Freeman Aug 17 '20 at 10:19
  • I dropped a suggestion for you – tmhao2005 Aug 17 '20 at 11:21
  • @EddyFreeman did you find a solution to this? – Ashish Dwivedi Mar 03 '21 at 13:18

2 Answers2

4

Since some vendors publish their sources without transpiling, so you need to transpile these packages again with babel-jest while ts-jest will take care ts files. In addition, you should transform these packages again by specifying transformIgnorePatterns. Here is your changed Jest config:

const esModules = ['@ckeditor', 'lodash-es'].join('|'); // you can put more if there is others

module.exports = {
  transform: {
    '^.+\\.(ts|html)$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
  },
  // ...
  transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
};

Just keep in mind, install babel, babel-jest & its preset and create the config for it:

// Install
npm i -D @babel/core @babel/preset-env babel-jest 

// babel.config.js
module.exports = function(api) {
  api.cache(true);

  const presets = ['@babel/preset-env'];
  const plugins = [];

  return {
    presets,
    plugins,
  };
};

tmhao2005
  • 14,776
  • 2
  • 37
  • 44
  • "@tmhao2005": thanks for the answer. I have done exactly what you said but it is not working. Is there a way i can test if the function in the babel.config.js is called? Can you also check this post https://github.com/vuejs/vue-test-utils-typescript-example/issues/6 where they use "@babel/plugin-transform-modules-commonjs" in the babel config. May be am still missing something. – Eddy Freeman Aug 17 '20 at 12:55
  • Can you share your minimal code which can replicate? – tmhao2005 Aug 17 '20 at 12:56
  • @EddyFreeman I can help if you give me enough context – tmhao2005 Aug 18 '20 at 06:10
  • "transformIgnorePatterns" – unfortunately some modules (like @ngrx) are released as TypeScript files, not pure JavaScript; in such cases we cannot ignore them (all node_modules are ignored by default), so they can be transformed through TS compiler like any other module in our project. https://thymikee.github.io/jest-preset-angular/docs/8.x/getting-started/options/ – Felix Oct 21 '21 at 17:56
1

I ran into the same issue when switching from lodash to lodash-es. I did what @tmhao2005 suggested and installed @babel/core, @babel/preset-env and babel-jest then added a babel.config.js in the root of my Nx Worspace and updated the base jest.config.ts. so you can try the following.

Install dependencies

yarn add -D @babel/core @babel/preset-env babel-jest
npm I -D @babel/core @babel/preset-env babel-jest

Add babel.config.js

In the root of your Nx Workspace add a babel.config.js with the following taken from the Jest docs

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ]
};

Update jest.config.ts

Update the base jest.config.ts in the root of your Nx Workspace to something like this depending on your configuration needs.

module.exports = {
    testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
    transform: {
        '^.+\\.(ts|html)$': 'ts-jest',
        '^.+\\.js$': 'babel-jest'
    },
    resolver: '@nrwl/jest/plugins/resolver',
    moduleFileExtensions: ['ts', 'js', 'html'],
    coverageReporters: ['html', 'json'],
    transformIgnorePatterns: ['/node_modules/(?!lodash-es)']
};

This approach worked for me using NX 10 for lodash-es but your mileage may vary with the @ckeditor packages. You will have to add all @ckeditor packages you want to the transformIgnorePatterns

Some possible helpful links

NX issue 1091
NX issue 812

Biffyn
  • 68
  • 8