Setting Up Jest for Compatibility with Compose SDK
Overview
The Compose SDK packages are built with ECMAScript Modules (ESM), while Jest, by default, expects CommonJS (CJS) modules. This difference creates compatibility challenges when using Jest for testing with Compose SDK. You can learn more about the differences between ESM and CJS in the Node.js official documentation. While Jest does provide experimental ESM support, it remains unstable and not recommended for production use.
Including CommonJS packages
Starting with version 1.22.0, Compose SDK packages include a CommonJS build alongside the ESM build. This allows you to configure Jest to use the CJS version of Compose SDK in tests, while the main application can continue using the ESM version.
File Structure for CJS in Compose SDK
- Primary Package (
sdk-ui): Includes.cjsfiles alongside.jsfiles within thedistfolder. - Other Packages (
sdk-common,sdk-data,sdk-modeling,sdk-query-client,sdk-rest-client,sdk-tracking): Contain acjsfolder within thedistdirectory, which houses the CJS build files.
Configuring Jest to Use CJS Packages
To direct Jest to the appropriate CJS files, you’ll use the moduleNameMapper configuration in your Jest config. This maps the ESM package paths to the CJS equivalents.
Note: Compose SDK uses the ESM version of lodash, so it’s also necessary to map lodash explicitly to its CJS version.
Here are suggested configurations for common frameworks:
Jest moduleNameMapper Configuration
React
"moduleNameMapper": {
"^@sisense/sdk-(common|data|modeling|query-client|rest-client|tracking)(.*)$": "<rootDir>/node_modules/@sisense/sdk-$1/dist/cjs$2",
"^@sisense/sdk-ui(.*)$": "<rootDir>/node_modules/@sisense/sdk-ui/dist$1",
"^lodash-es(.*)$": "<rootDir>/node_modules/lodash$1"
}
Angular
"moduleNameMapper": {
"^@sisense/sdk-(common|data|modeling|query-client|rest-client|tracking)(.*)$": "<rootDir>/node_modules/@sisense/sdk-$1/dist/cjs$2",
"^@sisense/sdk-ui-angular(.*)$": "<rootDir>/node_modules/@sisense/sdk-ui-angular/dist/fesm2020/sisense-sdk-ui-angular.mjs",
"^lodash-es(.*)$": "<rootDir>/node_modules/lodash$1"
}
Vue:
"moduleNameMapper": {
"^@sisense/sdk-(common|data|modeling|query-client|rest-client|tracking)(.*)$": "<rootDir>/node_modules/@sisense/sdk-$1/dist/cjs$2",
"^@sisense/sdk-ui-vue(.*)$": "<rootDir>/node_modules/@sisense/sdk-ui-vue/dist$1",
"^lodash-es(.*)$": "<rootDir>/node_modules/lodash$1"
}
Conclusion
By mapping the necessary Compose SDK packages to their CJS builds, Jest can effectively work with Compose SDK. This setup ensures that testing compatibility is maintained without impacting the main application’s use of ESM.