无法测试使用翻译管道的组件(找不到管道 'translate')

Unable to test component that uses translation pipe (The pipe 'translate' could not be found)

我有一个使用 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();
  });
});

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

您只需将模块导入您的测试台(就像您导入任何其他模块一样,例如 HttpModule 或 RouterModule)。例如:

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (http: Http) => new TranslateStaticLoader(http, 'public/assets/i18n', '.json'),
            deps: [Http]
        })],
        declarations: [SidenavComponent] // declare the test component
    });
});

在您的 testBed 配置中添加 imports TranslateModule 就像您在 appModule 或声明组件的模块中所做的那样。例如:

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

也许你有其他翻译配置。

您可以创建模拟管道:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
    name: "translate"
})
export class MockTranslatePipe implements PipeTransform {
    public name: string = "translate";

    public transform(query: string, ...args: any[]): any {
        return query;
    }
}

这个模拟管道可以在 describe 上方的规范文件中,或者您可以使用 translate-mock.pipe.ts 创建一个模拟文件夹,然后在规范文件中导入 MockTranslatePipe(因此您不需要编写此代码对于每个规范文件)。

  • 然后添加 MockTranslatePipein 声明:
TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [GenericChecklistComponent, **MockTranslatePipe**],
      imports: [MatMenuModule],
      providers: [
        { provide: TranslateService, useFactory: translateServiceStub }
      ]
    })
      .compileComponents();