Errors running tests using Angular v13 + Jest + ESM + NGXS

Issue

The migration from Angular v12 to v13 has been tough and while the app functions perfectly, the tests are still a problem on our side.

We have been running v12 tests using Jest with ESM (because we have a WebWorker and the import.meta.url requires ESM since v12) successfully as of now.

But now that v13 ships with only ES Modules it breaks in some third party libraries requiring angular code.

Now that the jest-preset-angular supports running v13 + ESM with a working example app I thought I’d give it another try. This is also being discussed in NGXS’s slack.

My current very basic config is the following:

const {pathsToModuleNameMapper} = require('ts-jest/utils');
const {paths} = require('./tsconfig.json').compilerOptions;
require('jest-preset-angular')

const esModules = ['tslib'].join('|');

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
    preset: 'jest-preset-angular/presets/defaults-esm',
    globals: {
        'ts-jest': {
            useESM: true,
            stringifyContentPathRegex: '\\.(html|svg)$',
            tsconfig: '<rootDir>/tsconfig-esm.spec.json',
        },
    },
    moduleNameMapper: {
        ...pathsToModuleNameMapper(paths, {prefix: '<rootDir>'}),
        tslib: 'tslib/tslib.es6.js',
    },
    transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};

I’ve gone through the documentation multiple times, I’m following migration issues being opened on different repo trying to address the issue.
I’ve also gone through the latest related issues including this.

Has anyone managed to have a working v13 + Jest + ESM + NGXS stack ? I can’t seem to figure it out.

For anyone who wants to fidget with a minimal reproduction repo, you can find it here. The tests run fine without ESM and fail using ESM because we end up trying to require @angular from the NGXS bundle.

Solution

I couldn’t make it work while preserving the import.meta.url syntax with Jest which requires Node to be run with the --experimental-vm-modules flag.

I noticed that I could run my test using a classic ESM config as long as the node flag wasn’t there.

So I resorted to transforming the import.meta.url syntax back to CommonJS in my test config using this babel plugin

Answered By – jbzen

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.