首页 > 解决方案 > 无法测试使用翻译管道的组件(找不到管道“翻译”)

问题描述

我有一个使用 ngx-translate 进行本地化的组件。创建模块的基本单元测试不起作用。它失败并出现以下错误:

PatientDataComponent should create FAILED
   [ERROR ->]{{ 'patient.information' | translate }}
  </p>
  The pipe 'translate' could not be found ("<p>[ERROR ->]{{ 'patient.information' | translate }}</p>"): ng:///DynamicTestModule/PatientDataComponent.html@1:2
error properties: Object({ ngSyntaxError: true, ngParseErrors: [ The pipe 'translate' could not be found ("<p>"): ng:///DynamicTestModule/PatientDataComponent.html@1:2 ] })

该应用程序能够切换语言;因此 ngx-translate 似乎有效。除了在我的单元测试中。测试代码如下所示:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PatientDataComponent } from './patient-data.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PatientDataComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PatientDataComponent);
    fixture.detectChanges();
  });

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

我需要做些什么来解决此错误并使组件可测试?

标签: angulartypescriptjasminengx-translate

解决方案


在您的 testBed 配置中添加您在 appModule 或声明组件的模块中所做imports的类似操作。TranslateModule例如:

TestBed.configureTestingModule({
  declarations: [PatientDataComponent],
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: I18nHttpLoaderFactory,
        deps: [HttpClient],
      },
    }),
  ],
}).compileComponents();

也许你有其他翻译配置。


推荐阅读