对于使用 jest 的 Angular v12 项目,我刚刚将 jest 更新到版本 28。但是现在,我收到以下错误
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)
这是我的 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"]
},
}
和 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,
// },
// }
};
当我向我的项目添加一个网络工作者时,我的测试出现了问题,该项目使用
import.meta.url
this.worker = new Worker(new URL('../webworkers/search.worker', import.meta.url), { type: 'module' });
有什么建议吗?
我遇到了同样的错误,并在这里找到了解决方案:在此处输入链接描述
yarn add --dev jest-environment-jsdom
我遇到了同样的问题,并注意到 jest-environment-jsdom 版本为 27。我安装了 v28 以匹配 jest 版本,它不再出现此错误。
我的测试仍然失败,所以 YMMV!
● 测试套件运行失败
TypeError: Cannot read properties of undefined (reading 'html')
at new JSDOMEnvironment (node_modules/jest-environment-jsdom/build/index.js:72:44)
我通过删除项目中的节点模块并重新安装依赖项来修复⤵️
Mac 操作系统
sudo npm install [email protected] --save-dev
节点版本
v18.14.0
包.json
"devDependencies": {
"@babel/preset-env": "^7.10.4",
"@testing-library/dom": "^7.20.0",
"@testing-library/jest-dom": "^5.11.0",
"@testing-library/user-event": "^12.0.11",
"babel-jest": "^26.1.0",
"jest": "^26.1.0",
"jest-environment-jsdom": "^29.4.3",
"jest-html-reporter": "^3.1.3"
}
您还可以尝试另一个版本的 jest-environment-jsdom
sudo npm install [email protected] --save-dev
应安装
jest-environment-jsdom
软件包,并且版本应与 jest
的版本匹配