Getting typeError: (options.astTransformers || []).map is not a function while running the test suite in Angular

Viewed 2249

I am getting below error while running jest test cases in Angular. All test suites are failing with this error.

Getting typeError: (options.astTransformers || []).map is not a function while running the test suite in Angular

5 Answers

This solution is for Angular 8/9/10

I would recommend doing these steps:

  1. Uninstall jest-preset-angular
  2. Reinstall jest-preset-angular
  3. Clear jest cache
  4. Retry

If the above solution not working, try installing

npm install --dev ts-jest

Fix this error by removing the following line in the jest.config.js file.

module.exports = {
    ...
    passWithNoTests: true,
    projects: '<rootDir>/libs/now-version' // <--- newly added property. should be removed
};

As I found this link on github. https://github.com/nrwl/nx/issues/3885#issuecomment-706620382

This error started after updating Angular to 11, and when I generate a new lib inside NX and it ends up adding this new line, whenever a new lib is generated, by the CLI

Seems to be a newer version of the package.

In the package.json I changed the jest-preset-angular from "8.3.2" to "8.2.0" and that error went away.

Updating the jest.config.js as below fixed my issue

module.exports = {
  displayName: 'AppName',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/libs/appName',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
  testRunner: 'jest-jasmine2'
};

Jest configuration for Angular can be tricky.

I recommend you use jest-preset-angular which is a library that you will import into your Angular project that will manage the configuration of Jest for Angular.

This may be related to the update of Jest 27 that deprecated astTransformers as string[].

Configure your Angular project to use Jest 26 with jest-preset-angular and you should be fine

Related