Angular 17.3.7中@angular-devkit/schematics的Jest测试报UTF-8编码无效
Angular 17.3.x 中 Schematics Jest 测试报 UTF-8 编码错误的修复方案
问题现象
- 三个 Angular 应用在 17.2.0 版本时,基于
@angular-devkit/schematics的 Jest 测试正常运行;升级至 17.3.7 后所有相关测试全部失败 - 新建的 17.3.7 测试专用应用也出现相同问题
- 普通 Jest 测试(如简单字符串断言)可正常通过,仅涉及 Schematics 的测试抛出错误:
The encoded data was not valid for encoding utf-8
测试代码示例
import { TextEncoder, TextDecoder } from 'util' global.TextEncoder = TextEncoder // @ts-expect-error global.TextDecoder = TextDecoder import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; const collectionPath = path.join(__dirname, '../collection.json'); describe('hello-world', () => { it('works', async () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = await runner.runSchematic('hello-world', {}, Tree.empty()); expect(tree.files).toEqual([]); }); it('works', async () => { const workspaceOptions = { name: 'workspace', newProjectRoot: 'projects', version: '7.0.0', }; const defaultAppOptions = { name: 'bar', inlineStyle: false, inlineTemplate: false, viewEncapsulation: 'Emulated', routing: false, style: 'css', skipTests: false }; const runner = new SchematicTestRunner('schematics', collectionPath); const workspaceTree = await runner.runExternalSchematic( '@schematics/angular', 'workspace', workspaceOptions ); const appTree = await runner.runExternalSchematic('@schematics/angular', 'application', defaultAppOptions, workspaceTree); const tree = await runner.runSchematic('hello-world', {}, appTree); expect(tree.files[0]).toEqual('/README.md'); }); });
项目核心依赖配置
{ "devDependencies": { "@angular-builders/jest": "^17.0.3", "@angular-devkit/build-angular": "^17.3.3", "@angular/cli": "^17.3.3", "jest": "^29.7.0", "typescript": "~5.4.2" } }
修复步骤
1. 修正全局 TextEncoder/TextDecoder 注入
原导入方式在 Angular 17.3.x 与 Jest 环境下存在实现冲突,改为从 node:util 导入并修正类型匹配:
// 替换原导入代码 import { TextEncoder, TextDecoder } from 'node:util'; global.TextEncoder = TextEncoder; global.TextDecoder = TextDecoder as typeof globalThis.TextDecoder;
移除 @ts-expect-error 注释,此时类型可正确匹配。
2. 对齐 @angular-builders/jest 版本
当前使用的 @angular-builders/jest@17.0.3 与 Angular 17.3.x 版本不兼容,升级至同大版本:
npm install @angular-builders/jest@^17.3.0 --save-dev
3. 配置 Jest 使用 Node 测试环境
在 jest.config.ts 中明确指定测试环境为 Node,并添加模块映射确保内置模块正确解析:
export default { testEnvironment: 'node', moduleNameMapper: { 'node:util': 'util', }, // 其他已有配置... };
4. 检查 Schematics 资源编码
确保 collection.json 及所有 Schematics 模板文件为纯 UTF-8 编码(无 BOM):
- 用 VS Code 打开文件,右下角确认编码为 UTF-8
- 若存在 BOM,通过「编码 > 以 UTF-8 无 BOM 编码保存」修正
验证
执行测试命令确认修复效果:
ng test
内容的提问来源于stack exchange,提问作者Catherine Clague
相关产品推荐
相关产品推荐

