Angular 6 个带有 ngx-translate 依赖的单元测试
Angular 6 unit testing with ngx-translate dependency
我有一个 angular 6
应用 ngx-translate/core@10.0.2
。尝试使用带有硬编码值的 CustomLoader
。但是有点不太对。
测试
class CustomLoader implements TranslateLoader {
getTranslation(lang: string): Observable<any> {
return of({
'DETAILS': {
'PIN_ENTRY': {
'INPUT': {
'ERRORS': {
'INVALID': 'Blah',
'INELIGIBLE': 'Blah Blah'
}
}
}
}
});
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [
... // Elided for brevity
TranslateModule.forRoot({
loader: { provide: TranslateLoader, useClass: CustomLoader}
})
],
})
.compileComponents();
}));
组件
ngOnInit() {
this.translateService.getTranslation('DETAILS.PIN_ENTRY.INPUT').pipe(first()).subscribe(translations => {
this.errorTranslations = translations['ERRORS'];
});
}
问题是,subscribe
中的 translate
总是 'DETAILS.PIN_ENTRY.INPUT'。我还在CustomLoader#getTranslation
里面加了一条logging语句,看是否加载了,但是看不到输出。
我的设置有什么问题?
当测试一个在 observable 中有值的组件时,您应该在测试中使用 async
或 fakeAsync
。
我认为 fakeAsync
可能是您的最佳选择:
describe('...', () => {
it('...', () => {
// create your component
// move forward in time
tick();
expect(component.errorTranslations).toEqual(yourError);
})
})
我有一个 angular 6
应用 ngx-translate/core@10.0.2
。尝试使用带有硬编码值的 CustomLoader
。但是有点不太对。
测试
class CustomLoader implements TranslateLoader {
getTranslation(lang: string): Observable<any> {
return of({
'DETAILS': {
'PIN_ENTRY': {
'INPUT': {
'ERRORS': {
'INVALID': 'Blah',
'INELIGIBLE': 'Blah Blah'
}
}
}
}
});
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [
... // Elided for brevity
TranslateModule.forRoot({
loader: { provide: TranslateLoader, useClass: CustomLoader}
})
],
})
.compileComponents();
}));
组件
ngOnInit() {
this.translateService.getTranslation('DETAILS.PIN_ENTRY.INPUT').pipe(first()).subscribe(translations => {
this.errorTranslations = translations['ERRORS'];
});
}
问题是,subscribe
中的 translate
总是 'DETAILS.PIN_ENTRY.INPUT'。我还在CustomLoader#getTranslation
里面加了一条logging语句,看是否加载了,但是看不到输出。
我的设置有什么问题?
当测试一个在 observable 中有值的组件时,您应该在测试中使用 async
或 fakeAsync
。
我认为 fakeAsync
可能是您的最佳选择:
describe('...', () => {
it('...', () => {
// create your component
// move forward in time
tick();
expect(component.errorTranslations).toEqual(yourError);
})
})