Jest 28: createJestExpect - TypeError: Cannot read properties of undefined (reading 'extend')

Viewed 1500

I migrated from Jest 27 to 28. If I try to start a test now, I just get this error:

  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'extend')

      at createJestExpect (node_modules/@jest/expect/build/index.js:35:19)
      at Object.<anonymous> (node_modules/@jest/expect/build/index.js:47:20)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:317:13)
      at runJest (node_modules/@jest/core/build/runJest.js:407:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:338:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:190:3)

Test Suites: 1 failed, 1 total

I can't even debug my tests, because the internal test setup is already failing. Any clue, what's going wrong?

2 Answers

This is a bug (see here) that appears when the moduleDirectories option includes ".".

A workaround is to use __dirname instead of .. You must however then use a jest.config.js configuration file instead of keeping the configuration in package.json:

// In `jest.config.js`
module.exports = {
  moduleDirectories: ["node_modules", __dirname]
};

i had a similiar error using angular together with jest. after updating jest and angular dependencies to the latest version i fixed this error in a slightly different way than Lupina but using rootDir instead of __dirname. 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/',
};
Related