我有一个使用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();
});
});
我该怎么办才能解决此错误并使组件可测试?
答案 0 :(得分:1)
您只需要将模块导入到您的测试床中即可(就像其他模块(例如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
});
});
答案 1 :(得分:1)
像在appModule或声明组件的模块中一样,在imports
中添加TranslateModule
。例如:
TestBed.configureTestingModule({
declarations: [PatientDataComponent],
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: I18nHttpLoaderFactory,
deps: [HttpClient],
},
}),
],
}).compileComponents();
也许您还有其他翻译配置。
答案 2 :(得分:0)
您可以创建一个模拟管道:
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上方的spec文件中,或者你可以用translate-mock.pipe.ts创建一个mock文件夹,然后在spec文件中导入MockTranslatePipe(所以你不需要为每个规范文件)。
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [GenericChecklistComponent, **MockTranslatePipe**],
imports: [MatMenuModule],
providers: [
{ provide: TranslateService, useFactory: translateServiceStub }
]
})
.compileComponents();