jeudi 26 novembre 2020

How to to unit test Angular pipe with TranslateService dependency

I have the following byte-size.pipe, which has dependency on ngx-translate TranslateService

import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'byteSize',
  pure: false,
})
export class ByteSizePipe implements PipeTransform {
  constructor(private translate: TranslateService) {}

  transform(bytes: any, decimals?: any): any {
    if (bytes === 0) {
      const loc: any = this.translate.instant('size.Bytes');
      return '0 ' + loc;
    }

    const k = 1024;
    const dm = decimals || 2;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const lang: any = this.translate.instant('size.' + sizes[i]);
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + lang;
  }
}

So far my test looks like:

import { TestBed, tick, fakeAsync, inject, async } from '@angular/core/testing';
import { ByteSizePipe } from './byte-size.pipe';

//Translation Dependecies
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { HttpLoaderFactory } from '../app.module';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TranslateTestingModule } from 'ngx-translate-testing';

describe('ByteSizePipe', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        TranslateTestingModule.withTranslations({ en: require('../../assets/langs/en.json') }).withDefaultLanguage('en'),
        HttpClientTestingModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient],
          },
        }),
      ],
      providers: [TranslateService],
    }).compileComponents();
  }))

  fit('Verify Byte Size transform', inject([TranslateService],  async (translateService: TranslateService) => {
    translateService.setDefaultLang('en');
    let pipe = new ByteSizePipe(translateService);
    expect(pipe.transform(1024)).toBe('1 KB');
  }));
});

When I run my test - expect(pipe.transform(1024)).toBe('1 KB'); It returns false with value of

1 size.KB So I get the translation label instead of the translation itself. How to make it work with translations?

Aucun commentaire:

Enregistrer un commentaire