mercredi 13 mars 2019

How to write a unit test in Angular that tests a simple service method

Since I have never written an Angular Unit Test, I would need help testing a simple service method.

The method takes an activeBusinessCase and returns a language as a string based on the taken activeBusinessCase. For example, if there is no business case specific translation, then the string "de" is returned and if there is a specific language, then "de_case1" is returned.

That's my method inside my configuration.service.ts:

  getAutoConfiguredBCLanguage$(): Observable<string> {
    return this.authService.activeBusinessCase$.pipe(
      distinctUntilChanged(),
      map(bc => this.getAutoConfiguredBCLanguage(bc))
    );
  }

  getAutoConfiguredBCLanguage(activeBusinessCase?: string) {
    const browserLang = this.translate.getBrowserLang();
    console.log('BROWSER LANGUAGE: ', browserLang);
    if (this.languages.hasOwnProperty(browserLang)) {
      switch (activeBusinessCase) {
        case 'CASE_1':
          return browserLang.concat(this.businessCases.case_1);
        case 'CASE_2':
          return browserLang.concat(this.businessCases.case_2);
        case 'CASE_2':
          return browserLang.concat(this.businessCases.case_3);
        default:
          return browserLang;
      }
    } else {
      return this.defaultLanguage;
    }
  }

And that is the current state of my test, of which I have no idea:

import { inject, TestBed } from '@angular/core/testing';

import { ConfigurationService } from './configuration.service';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { multiTranslateHttpLoaderFactory } from '../app.component';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { UserAuthService } from 'app/auth/user-auth.service';

describe('ConfigurationService', () => {

  let config: ConfigurationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ConfigurationService],
      imports: [
        HttpClientTestingModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: multiTranslateHttpLoaderFactory,
            deps: [HttpClient, UserAuthService]
          }
        }),
      ]
    });
  });

  it('should ...', inject([ConfigurationService], (service: ConfigurationService) => {
    expect(service).toBeTruthy();
  }));


  describe('#parseUiInfo', () => {
    it('should return a default or business case specific language', () => {
      config.getAutoConfiguredBCLanguage();
      // TODO
    });

  });

});

Can someone help me please?

Aucun commentaire:

Enregistrer un commentaire