Angular 14 and Jest (cannot run tests)

Viewed 823

I am upgrading Angular version in my project to 14. But when I tried to run unit tests, I get the same error for all of them:

  ● Test suite failed to run

    Cannot find module '@angular/core/testing' from 'node_modules/jest-preset-angular/build/config/setup-jest.js'

    Require stack:
      node_modules/jest-preset-angular/build/config/setup-jest.js
      node_modules/jest-preset-angular/setup-jest.js
      setupJest.ts

This is the current jest configuration:

jest.config.js

/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setupJest.ts'],
  testPathIgnorePatterns: [
    '<rootDir>/node_modules/',
    '<rootDir>/dist/'
  ],
  moduleNameMapper: {
    "lodash-es": "lodash",
  },
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.html$',
      diagnostics: {
        ignoreCodes: [151001]
      }
    }
  },
  restoreMocks: true,
  clearMocks: true
}

module.exports = config;

setupJest.ts

import 'jest-preset-angular/setup-jest';
3 Answers

So I was searching online for quite sometime then I came across this solution, hope it works for you as well.

In the jest.config.js file, if you are using the moduleDirectories config change it from moduleDirectories: ['node_modules', './'] to moduleDirectories: ['node_modules', __dirname]

I wasnt able to fix the problem with the solution provided by fadingbear but it inspired me to change './' to ''. So after updating jest, jest-preset-angular and angular to the latest version I got this fixed by using moduleDirectories: ['node_modules', '<rootDir>'], in my jest.config.js instead of ['node_modules', './']

I also had to add the transformIgnorePatterns entry to get rid of any unexpected token errors like described in the troubleshooting section of the jest-preset-angular documentation: https://thymikee.github.io/jest-preset-angular/docs/guides/troubleshooting

This is my current jest.config.js

// jest.config.js
module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
  moduleDirectories: ['node_modules', '<rootDir>'],
  transformIgnorePatterns: ['node_modules/(?!@angular|rxjs)'],
  collectCoverage: true,
  coverageDirectory: '<rootDir>/coverage/',
};

When I have this type of error, I usually add required path to Jest configuration in package.json:

"modulePaths": [
 "<rootDir>",
 "/path/to/required"
],

However, this approach is more suitable for situations where required path is, for example, src/app/.

For node_modules, I solved the problem by adding "transformIgnorePatterns": ["/node_modules/?!@angular"], to package.json Jest configuration.

Also, I would advise you to hit npm install from the root folder. Just in case :)

Related