'Cannot read property 'html' of undefined after jest update

For an angular v12 project which uses jest I just updated jest to version 28. Now, however, I get the following error

FAIL  src/app/components/update-input/update-input.directive.spec.ts
● Test suite failed to run

  TypeError: Cannot read property 'html' of undefined

    at new JSDOMEnvironment (node_modules/jest-environment-jsdom/build/index.js:72:44)

Here is my tsconfig.spec.json

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

and jest.config.js

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

module.exports = {
  preset: "jest-preset-angular",
  // preset: 'jest-preset-angular/presets/defaults-esm',
  roots: ["<rootDir>/src/"],
  testMatch: ["**/+(*.)+(spec).+(ts)"],
  setupFilesAfterEnv: ["<rootDir>/src/test.ts"],
  collectCoverage: true,
  coverageReporters: ["html"],
  coverageDirectory: "coverage/app",
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
    prefix: "<rootDir>/",
  }),
  transform: {
    '^.+\\.(ts|js|html|svg)$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'js', 'html', 'svg'],
  // extensionsToTreatAsEsm: ['.ts'],
  // globals: {
  //   'ts-jest': {
  //     tsconfig: '<rootDir>/tsconfig.spec.json',
  //     stringifyContentPathRegex: '\\.html$',
  //     useESM: true,
  //   },
  // }
};

The problems with my tests started when I added a web-worker to my project, which uses import.meta.url

 this.worker = new Worker(new URL('../webworkers/search.worker', import.meta.url), { type: 'module' });

Any suggestion what is going on here and how to fix this?



Solution 1:[1]

I had this same issue and noticed that jest-environment-jsdom was on version 27. I installed v28 to match the jest version and it stopped giving this error.

My tests are still failing so YMMV!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lydia