use*_*668 13 angular-cli angular2-testing ng2-translate angular
我正在使用angular2进行组件测试.在我的html模板中,我使用翻译管道.这是测试的代码:
import { ComponentFixture, TestBed ,getTestBed} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RightComponent } from './right.component';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {Injector} from "@angular/core";
let comp: RightComponent;
let fixture: ComponentFixture<RightComponent>;
let el: DebugElement;
let translate: TranslateService;
let injector: Injector;
describe('testComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ RightComponent ]
});
injector = getTestBed();
translate = injector.get(TranslateService);
fixture = TestBed.createComponent(RightComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// get title DebugElement by element name
el = fixture.debugElement.query(By.css('h2'));
});
it('should display original title', () => {
fixture.detectChanges(); // trigger data binding
expect(el.nativeElement.textContent).toContain('Liste des droits');
});
});
Run Code Online (Sandbox Code Playgroud)
我得到这个错误,翻译管道不知道:
Error: Template parse errors:
The pipe 'translate' could not be found ("<h2>[ERROR ->]{{'RIGHT_TITLE' | translate}}</h2>
<div class="table-responsive">
<table id="rightTableId" clas"): RightComponent@0:4
The pipe 'translate' could not be found ("
<table id="rightTableId" class="table table-striped">
<tr>
<th>[ERROR ->]{{'NAME_LABEL' | translate}}</th>
</tr>
<tr *ngFor="let right of rights">
"): RightComponent@4:16
The pipe 'translate' could not be found ("
</tr>
<tr *ngFor="let right of rights">
<td>[ERROR ->]{{right.name | translate}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
我们如何解决这个问题?
谢谢.
Pau*_*tha 23
这是ng2-translate github.com/ocombe/ng2-translate
您需要TestBed使用库模块进行配置,就像使用实际应用程序配置库一样.查看文档,它显示了通过导入模块进行配置
imports: [
TranslateModule.forRoot()
]
Run Code Online (Sandbox Code Playgroud)
所以你应该在TestBed配置中做同样的事情
TestBed.configureTestingModule({
declarations: [ RightComponent ],
imports: [TranslateModule.forRoot()]
});
Run Code Online (Sandbox Code Playgroud)
这就是TestBed.configureTestingModule:为测试环境配置模块.
与最新的 Angular 4 兼容,ngx-translate您需要将其直接实现到要测试的组件中:
import {TranslateHttpLoader} from "@ngx-translate/http-loader";
import {Http, HttpModule} from "@angular/http";
import {
MissingTranslationHandler,
TranslateLoader,
TranslateModule,
TranslateService
} from "@ngx-translate/core";
...
export function HttpLoaderFactory(http: Http) {
return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}
...
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [Http]
}
})
],
...
providers: [
TranslateService
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14513 次 |
| 最近记录: |