Jasmine - how to test HttpLoaderFactory from @ngx-translate

61 Views Asked by At

I'm writing Angular app with @ngx-translate dependency so I configured package according to doc:

https://github.com/ngx-translate/core?tab=readme-ov-file#configuration

app.module.ts

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';

import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';

import { AppComponent } from './main';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    TranslateModule.forRoot({
      defaultLanguage: 'en',
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient],
      },
    }),
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

Then, my Jasmine code coverage raport says I should test HttpLoaderFactory.

enter image description here

I am wondering how can I do this? Code on stackblitz

1

There are 1 best solutions below

3
Naren Murali On BEST ANSWER

We can create a separate describe block, which is just plain jasmine unit testing for this function, to cover this function, we can use the below code.

Its really difficult to test this scenario, so I am initializing the TranslateHttpLoader with the same params and comparing the returned value with the intialized value!

import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { HttpLoaderFactory } from './app.module';

describe('should cover HttpLoaderFactory', () => {
  it('should initialize TranslateHttpLoader with params', () => {
    const httpClient = {} as any;
    const returnValue = HttpLoaderFactory(httpClient);
    expect(returnValue).toEqual(
      new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json')
    );
  });
});

Stackblitz Demo