我无法在组件上运行Jest测试,因为它无法加载html文件。我知道这个错误:
Error: Error: connect ECONNREFUSED 127.0.0.1:80其次是:
Unhandled Promise rejection: Failed to load landing.component.html运行非组件测试是可以的。
这是我的jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "jest-preset-angular",
testEnvironment: "jsdom",
setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
globals: {
"ts-jest": {
tsconfig: "<rootDir>/tsconfig.spec.json",
stringifyContentPathRegex: "\\.(html|svg)$",
},
},
snapshotSerializers: [
"jest-preset-angular/build/serializers/html-comment",
"jest-preset-angular/build/serializers/ng-snapshot",
"jest-preset-angular/build/serializers/no-ng-attributes",
],
moduleDirectories: ["node_modules", "."],
testMatch: ["**/+(*.)+(spec|test).+(ts|js)?(x)"],
transform: {
"^.+\\.(ts|js|html)$": "ts-jest",
},
resolver: "@nrwl/jest/plugins/resolver",
moduleFileExtensions: ["ts", "js", "html"],
coverageReporters: ["html"],
};我的setup-jest.ts
import 'jest-preset-angular/setup-jest';还有我的tsconfig.spec.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"module": "commonjs",
"types": ["jest", "node"],
"allowJs": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true
},
"files": ["setup-jest.ts"],
"include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}来自angular.json的Jest部分
"test": {
"builder": "@nrwl/jest:jest",
"options": {
"jestConfig": "jest.config.js",
"passWithNoTests": true
}
}我使用角12.2.7,Jest 27.2.4,jest-预设-角10.0.1和ts-jest 27.0.5。
发布于 2022-02-20 03:07:59
This answer帮助我解决了这个问题。由于只有链接的答案是不鼓励的,下面我已经包括了原来的答案由bnjmnhndrsn.
我最近遇到了这个特定的问题,创建自己的转换预处理器将解决这个问题。这是我的设计:
package.json
"jest": {
"moduleFileExtensions": [
"js",
"html"
],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
}
}注意:默认情况下,babel-jest通常包括在内,但是如果您指定了自定义转换预处理程序,则似乎必须手动包含它。
test/utils/htmlLoader.js:
const htmlLoader = require('html-loader');
module.exports = {
process(src, filename, config, options) {
return htmlLoader(src);
}
}https://stackoverflow.com/questions/69863320
复制相似问题