You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目Jest单元测试中Transloco翻译缺失警告修复

解决Jest测试中Transloco提示'enUS.MAIN_LAYOUT.MAX_CHARACTER_COUNT'缺失的问题

问题原因

测试环境中Transloco会自动尝试匹配系统的区域语言(比如en-US),但你的项目仅配置了en和ru两种根语言,找不到对应en-US的翻译文件,因此触发缺失警告。

解决方案

方案1:测试中手动指定激活语言

在测试代码里显式设置Transloco的默认语言和激活语言,强制使用项目已配置的en:

import { HttpClientModule } from '@angular/common/http';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslocoService } from '@ngneat/transloco';

import { TranslocoRootModule } from '../../../transloco-root.module';
import { MyModalComponent } from './my-modal.component';

describe('MyModalComponent', () => {
  let component: MyModalComponent;
  let fixture: ComponentFixture<MyModalComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, TranslocoRootModule],
      declarations: [MyModalComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [NgbActiveModal, TranslocoService],
    });
    
    // 新增:手动设置Transloco语言
    const translocoService = TestBed.inject(TranslocoService);
    translocoService.setDefaultLang('en');
    translocoService.setActiveLang('en');
    
    fixture = TestBed.createComponent(MyModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

方案2:配置Transloco语言回退

在transloco-root.module.ts中添加回退规则,让en-US自动 fallback 到en,一劳永逸解决所有同类测试警告:

export function getTranslocoModule(): TranslocoModule {
  return TranslocoModule.forRoot({
    config: {
      availableLangs: ['en', 'ru'],
      defaultLang: 'en',
      // 添加回退配置
      fallbackLang: {
        'en-US': 'en',
        'ru-RU': 'ru' // 可选:针对俄语区域语言也做回退
      },
      // 其他现有配置...
    },
    // 其他模块配置...
  });
}

方案3:优化组件翻译逻辑(推荐)

当前组件在初始化时直接调用translate(),属于提前执行翻译,不符合Transloco最佳实践。改为延迟翻译,既能解决测试警告,还能支持语言切换时自动更新提示:

inputValidatorsParamMap: Map<string, ValidationParams> = new Map([
  [
    'noMoreThan100Symbols',
    {
      regex: /^.{0,100}$/,
      // 改为返回翻译函数,在验证触发时再执行翻译
      message: () => this.translocoService.translate('MAIN_LAYOUT.MAX_CHARACTER_COUNT', { count: 100 })
    } as ValidationParams,
  ],
]);

后续在验证逻辑中调用message()方法获取翻译后的提示文本即可。

内容的提问来源于stack exchange,提问作者Maksat Madeniyetov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:42:20