Angular Jasmine测试-不执行onLangChange回调

时间:2018-12-19 16:11:01

标签: angular jasmine rxjs karma-jasmine

我刚刚开始为Angular项目编写单元测试,如果设置了语言,我在测试中会遇到一些问题。

这是我的app.component.ts的代码:

ngOnInit() {
    this.translateService.setDefaultLang('en');

    this.translateService.onLangChange.subscribe((langChangeEvent: LangChangeEvent) => {
        this.localStorageService.setItem(LocalStorageService.languageKey, langChangeEvent.lang);
    });
    this.translateService.use('en');  <---- The subscribe callback should be called
}

这是我的app.component.spec.ts的代码:

  describe('ngOnInit', () => {
    it('should set default language as en', () => {
      const translateService = fixture.debugElement.injector.get(TranslateService);
      spyOn(translateService, 'setDefaultLang');
      component.ngOnInit();
      expect(translateService.setDefaultLang).toHaveBeenCalledWith('en');
  }); <----- This part of test is successful



    it('should set new lang key to localStorageService on TranslateService.onLangChange observable emit', () => {
      const localStorageService = fixture.debugElement.injector.get(LocalStorageService);
      spyOn(localStorageService, 'setItem');
      component.ngOnInit();
      translateService.use('de');
      expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
  });<-------------This test throws error (see below)

}); 

我收到此错误:

enter image description here

我在应用中测试了执行订阅回调的方法,但是测试却没有执行。我在这里完全误解了整个单元测试的概念吗?我在做什么错了?

编辑:

根据dmcgrandle的请求-发布完整的app.component.spec.ts:

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import {TranslateModule ,TranslateService, LangChangeEvent} from "@ngx-translate/core";
import {LocalStorageService} from "./core/local-storage.service";
import {OAuthService, UrlHelperService} from "angular-oauth2-oidc";
import {HttpClientModule} from "@angular/common/http";
import {ConfigurationService} from "./core/configuration.service";
import {MockConfigurationService} from './testing/mock-services/configuration.service.mock';
import { of } from 'rxjs/observable/of';
import * as fastClick from 'fastclick';

describe('AppComponent', () => {
  const mockFastClick = jasmine.createSpyObj('fastClick', ['attach']);
  let component : AppComponent;
  let fixture;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
        RouterTestingModule.withRoutes([]),
        TranslateModule.forRoot(),
        HttpClientModule

      ],
      providers:[
        TranslateService,
        LocalStorageService,
        OAuthService,
        UrlHelperService,
        { provide: fastClick, useValue: mockFastClick },
        { provide: ConfigurationService, useValue: MockConfigurationService }
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
  });

  it('should create the app', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should call fastClick.attach', () => {
        spyOn(fastClick, 'attach');
        component.ngOnInit();
        expect(fastClick.attach).toHaveBeenCalledWith(document.body, null);
    });
    it('should have loaded config', () => {
      fixture.detectChanges();
      const appConfig = fixture.debugElement.injector.get(ConfigurationService);
      expect(component.appConfig).toEqual(appConfig.config);
    });
    it('should set default language as en', () => {
      const translateService = fixture.debugElement.injector.get(TranslateService);
      spyOn(translateService, 'setDefaultLang');
      component.ngOnInit();
      expect(translateService.setDefaultLang).toHaveBeenCalledWith('en');
  });
   it('should set new lang key to localStorageService on TranslateService.onLangChange observable emit', () => {
      const localStorageService = fixture.debugElement.injector.get(LocalStorageService);
      spyOn(localStorageService, 'setItem');
      component.ngOnInit();
      expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
  });

});

});

1 个答案:

答案 0 :(得分:1)

不确定这是否会有所帮助,但是我会以此为答案,以防万一,不幸的是,我没有办法自己进行测试。

我将尝试通过模拟在您的provider数组中模拟TranslateService来解决这个问题。也许像这样(但模拟所有需要的方法):

class TranslateServiceStub {
    setDefaultLang(lang: string) { }
    use(lang: string) { }
    get onLangChange() { return of({lang: 'en'}) }
}

然后在您的提供商数组中更改TestBed

TranslateService,

{ provide: TranslateService, useClass: TranslateServiceStub },

然后在您的规范中,您可以更改获取器的返回值

it('should set new lang key to localStorageService on TranslateService.onLangChange observable emit', () => {
      const localStorageService = fixture.debugElement.injector.get(LocalStorageService);
      const translateService = fixture.debugElement.injector.get(TranslateService);
      spyOnProperty(translateService, 'onLangChange', 'get').and.returnValue(of({lang: 'de'}));
      spyOn(localStorageService, 'setItem');
      component.ngOnInit();
      expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
  });

但是正如我在上面的评论中提到的那样,显然这是一项特别难于模拟的服务。

祝你好运。 :)