如何在Angular中编写测试简单服务方法的单元测试

时间:2019-03-13 10:14:39

标签: angular unit-testing testing angular-test

由于我从未编写过Angular单元测试,因此需要测试简单服务方法的帮助。

该方法采用activeBusinessCase并基于所采用的activeBusinessCase以字符串形式返回语言。例如,如果没有特定于业务案例的翻译,则返回字符串“ de”,如果存在特定的语言,则返回“ de_case1”。

这是我的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;
    }
  }

这是我测试的当前状态,我不知道:

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
    });

  });

});

有人可以帮我吗?

0 个答案:

没有答案