Search code examples
jestjsbabeljsangular10ckeditor5babel-jest

Using CKEditor with Angular and Jest


I am using CKEditor5 in my Angular 10 app. After a long and somewhat painful integration process, CKEditor is working perfectly in the application. The application is structured as an nx monorepo if that makes a difference.

However, I am now unable to run some of the unit tests for my app. Any unit tests for a component that uses CKeditor (around 5 components at present) now fail with the following error:

C:\path\to\my\repo\node_modules@ckeditor\ckeditor5-watchdog\src\editorwatchdog.js:12

import { throttle, cloneDeepWith, isElement } from 'lodash-es';

^^^^^^

SyntaxError: Cannot use import statement outside a module

It seems that I will need to use Babel to transform the imports in editorwatchdog.js so that Jest may understand them. To solve this, I have installed @babel/core 7.13.8, @babel/preset-env 7.13.9, and babel-jest 26.6.3 (note, I already had jest 26.2.2 installed)

I have added a babel.config.js file to the root of my project, which contains only this:

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

And lastly, I have updated my root jest.config.js file to include the transform and transformIgnorePatterns keys:

module.exports = {
  transform: {},
  transformIgnorePatterns: "\\\\/node_modules\\\\/(?!@ckeditor).+\\.(js|jsx|ts|tsx)$",
  projects: [
    ... // all my libs and apps
  ]
}

(note: I also tried adding the transform and transformIgnorePatterns to the package.json)

But when I run my tests with the above changes in place, I still see the same error message as before. Clearly I am missing something, but what?

End result is that I need Babel to only transform @ckeditor files, and only when running the unit tests.


Solution

  • I'm using Jest to test React application with CKEditor 5 component.

    You get this error because Jest does not support fully ECMAScript modules.

    First, you need to tell Jest to transform CKEditor 5 code:

    // jest.config.ts
    export default {
      // ...
      transformIgnorePatterns: [
        '\\\\/node_modules\\\\/(?!@ckeditor).+\\.(js|jsx|ts|tsx)$',
        '\\.pnp\\.[^\\/]+$'
      ],
    }
    

    This will transpile CKEditor5 modules but you'll run into similar errors for SVG:

    SyntaxError: Unexpected token '<'

    or CSS files:

    .ck.ck-placeholder,

    ^

    SyntaxError: Unexpected token '.'

    This is because CKEditor 5 uses webpack's file-loader to load SVG files. This can be overcome by mocking any SVG or CSS file:

    // jest.config.ts
    export default {
      // ...
      moduleNameMapper: {
        '\\.(svg|css)$': '<rootDir>/test/__mocks__/fileMock.js',
      },
    }