3cn-ecn/nantralPlatform

jest doesn't perfectly work

Closed this issue · 1 comments

Due to ESM compatibility problem, jest can't run test on the Calendar component (and that can be the case of other imported modules, but not enough tests are implemented to see this).

image

Here the problem come from nanoid which is imported with "require" in the ics library

If it can be for any help, we have 3 ways to solve this problem.

What is the bug exactly?

Jest does not support ESM modules, ie the files which uses import ... from syntax instead of CommonJS (const ... = require(...)). These files must be transformed before giving them to jest.

How to solve?

  • Solution 1: Tell jest to replace the lib which uses ESM by its equivalent in CommonJS. It is the solution we used for lodash for example:
     // jest.config.ts
     moduleNameMapper: {
     // lodash-es (ESM version) is replaced by lodash (CommonJS) in tests
     '^lodash-es$': 'lodash',
     }
  • Solution 2: Create a mock to simulate the library. This is the solution we use for CKEditor as an example:
     // Home.page.test.tsx
     jest.mock('#shared/ckeditor/CustomEditor.ts');
     
     // src/shared/ckeditor/__mocks__/CustomEditor.ts
     export class CustomEditor {
        static builtinPlugins = [];
        static defaultConfig = {};
        config: unknown;
        constructor(config) { this.config = config; }
        init() { return Promise.resolve(); }
        destroy() { return Promise.resolve(); }
     }
  • Solution 3: tell jest to compile the library to CommonJS, by adding an exception to the node_modules. However this will slow down the tests.
     // jest.config.ts
     transformIgnorePatterns: [
         "/node_modules/(?!lodash-es|@ckeditor/core|other_libs_need_transform)"
     ],