Jest tests fail when trying to import date-fns in Angular project

I recently updated one of my Angular projects to Angular 13. After the updates I got some weird errors when trying to run the unit tests in the project.

I created a minimal example inside a fresh Angular project to reproduce this behavior:

import { format } from 'date-fns';
import { de } from 'date-fns/locale';


describe('AppComponent', () => {
  it('date-fns should work', () => {
    const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy', { locale: de });
    expect(result).toEqual('02/11/2014');
  });
});

When i execute npm run test the test fails and produces the following output:

/home/marco/dev/jest-test/node_modules/date-fns/esm/locale/index.js:2
    export { default as af } from "./af/index.js";
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | import { format } from 'date-fns';
    > 2 | import { de } from 'date-fns/locale';
        | ^
      3 |
      4 | describe('AppComponent', () => {
      5 |   it('date-fns should work', () => {

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/app/app.component.spec.ts:2:1)

This is my jest.config.js:

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

module.exports = {
    preset: 'jest-preset-angular',
    roots: ['<rootDir>/src/'],
    testMatch: ['**/+(*.)+(spec).+(ts)'],
    setupFilesAfterEnv: ['<rootDir>/src/test.ts'],
    collectCoverage: true,
    coverageReporters: ['html'],
    coverageDirectory: 'coverage/my-app',
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
        prefix: '<rootDir>/'
    })
};

And this my tsconfig.spec.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jest",
      "node"
    ],
    "esModuleInterop": true,
    "emitDecoratorMetadata": true
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

Any help is appreciated!


I solved my problem by adding date-fns and .mjs to the transformIgnorePatterns as suggested in the jest-preset-angular migration guide.

module.exports = {
    // ...other options
    transformIgnorePatterns: ['<rootDir>/node_modules/(?!(.*\\.mjs)|date-fns)']
};