paj*_*vic 5 jestjs angular ts-jest
我无法在我的组件上运行 Jest 测试,因为它无法加载 html 文件。我收到此错误:
Error: Error: connect ECONNREFUSED 127.0.0.1:80
Run Code Online (Sandbox Code Playgroud)
其次是:
Unhandled Promise rejection: Failed to load landing.component.html
Run Code Online (Sandbox Code Playgroud)
运行非组件测试就可以了。
这是我的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"],
};
Run Code Online (Sandbox Code Playgroud)
我的setup-jest.ts
import 'jest-preset-angular/setup-jest';
Run Code Online (Sandbox Code Playgroud)
和我的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"]
}
Run Code Online (Sandbox Code Playgroud)
和笑话部分来自angular.json
"test": {
"builder": "@nrwl/jest:jest",
"options": {
"jestConfig": "jest.config.js",
"passWithNoTests": true
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 Angular 12.2.7、Jest 27.2.4、jest-preset-Angular 10.0.1 和 ts-jest 27.0.5。
这个答案帮助我解决了这个问题。由于不鼓励仅链接答案,下面我包含了bnjmnhndrsn的原始答案。
我最近遇到了这个特定问题,创建您自己的转换预处理器将解决它。这是我的设置:
包.json
"jest": {
"moduleFileExtensions": [
"js",
"html"
],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
}
}
Run Code Online (Sandbox Code Playgroud)
注意:babel-jest 通常是默认包含的,但如果您指定自定义转换预处理器,则似乎必须手动包含它。
测试/utils/htmlLoader.js:
const htmlLoader = require('html-loader');
module.exports = {
process(src, filename, config, options) {
return htmlLoader(src);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1259 次 |
| 最近记录: |