Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'html' of undefined after jest update

Tags:

angular

jestjs

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?

like image 484
Jeanluca Scaljeri Avatar asked Sep 06 '25 03:09

Jeanluca Scaljeri


2 Answers

I had the same error and found the solution here: enter link description here

yarn add --dev jest-environment-jsdom
like image 182
Jean Claveau Avatar answered Sep 07 '25 22:09

Jean Claveau


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!

like image 44
Lydia Avatar answered Sep 08 '25 00:09

Lydia