Angular项目单元测试报错:无法读取undefined的'reRenderOnLangChange'属性
TypeError: Cannot read properties of undefined (reading 'reRenderOnLangChange')
at shouldListenToLangChanges (node_modules/@ngneat/transloco/fesm2022/ngneat-transloco.mjs:385:33)
at TranslocoPipe.transform (node_modules/@ngneat/transloco/fesm2022/ngneat-transloco.mjs:1313:36)
at ɵɵpipeBind1 (node_modules/@angular/core/fesm2022/core.mjs:27718:22)
at templateFn (ng:///DocumentToPrintRowComponent.js:68:34)
at executeTemplate (node_modules/@angular/core/fesm2022/core.mjs:12159:9)
at refreshView (node_modules/@angular/core/fesm2022/core.mjs:13392:13)
at detectChangesInView (node_modules/@angular/core/fesm2022/core.mjs:13617:9)
at detectChangesInViewIfAttached (node_modules/@angular/core/fesm2022/core.mjs:13580:5)
at detectChangesInComponent (node_modules/@angular/core/fesm2022/core.mjs:13569:5)
at detectChangesInChildComponents (node_modules/@angular/core/fesm2022/core.mjs:13630:9)
这个错误源于测试环境未正确初始化Transloco配置,导致TranslocoPipe无法获取reRenderOnLangChange配置项,以下是具体修复方案:
方案一:导入Transloco测试模块
在组件测试配置中,导入TranslocoTestingModule并配置基础语言数据,确保管道能正常读取配置:
import { TranslocoTestingModule } from '@ngneat/transloco'; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ // 配置测试用语言包,示例为英文 TranslocoTestingModule.withLangs({ en: { hello: 'Hello' } }, { defaultLang: 'en', reRenderOnLangChange: true // 显式声明该配置 }), // 其他必要依赖模块 ], declarations: [DocumentToPrintRowComponent] }).compileComponents(); });
方案二:Mock Transloco服务
若不想引入完整测试模块,可提供Mock的TranslocoService,包含管道所需的核心配置:
import { TranslocoService } from '@ngneat/transloco'; import { of } from 'rxjs'; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [DocumentToPrintRowComponent], providers: [ { provide: TranslocoService, useValue: { getConfig: () => ({ reRenderOnLangChange: true }), // 按需添加其他必要方法,比如翻译查询方法 selectTranslate: () => of('mock-translation') } } ] }).compileComponents(); });
方案三:检查模板中管道使用
确认组件模板内TranslocoPipe的语法是否正确,比如翻译键值是否传递无误,避免因参数错误引发间接报错,但核心问题仍以测试环境配置修复为主。
内容的提问来源于stack exchange,提问作者Francesco Borzi

