I have a simple Angular component with translatable text content, which I want to test. Unfortunately, the text content of my component is always empty when running my Jasmine/Karma tests.
However, the translated text is displayed when running the application itself and I can even receive the translation directly from TranslateService
in a separate Jasmine test.
How can I fix displaying the translated text in my HTML template for Jasmine/Karma?
My component "foo.component.ts":
@Component({selector: 'app-foo', template: `<p>{{ 'hello' | translate }}</p>`})
export class FooComponent {
}
My translation file "assets/i18n/en.json":
{
"hello": "Hello World!"
}
My test "foo.component.spec.ts":
const createTranslateHttpLoader = (http: HttpClient) => new TranslateHttpLoader(http);
describe('FooComponent', () => {
let component: FooComponent;
let fixture: ComponentFixture<FooComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FooComponent],
imports: [
HttpClientModule,
TranslateModule.forRoot({
loader: {provide: TranslateLoader, useFactory: createTranslateHttpLoader, deps: [HttpClient]},
defaultLanguage: 'en'
})
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should display greeting', () => { // <= fails
expect(fixture.nativeElement.textContent).toBe('Hello World!');
});
it('has greeting translation', async () => { // <= works
const translation = await TestBed.inject(TranslateService).get('hello').toPromise();
expect(translation).toBe('Hello World!');
});
});
I'm using Angular 11.0.1 and ngx-translate 13.0.0.
question from:
https://stackoverflow.com/questions/65847939/ngx-translate-fails-to-resolve-translations-when-running-jasmine-karma-tests 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…