Angular Jasmine 测试 - onLangChange 回调未执行

gfe*_*els 2 jasmine rxjs karma-jasmine angular

我刚刚开始为我的 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
}
Run Code Online (Sandbox Code Playgroud)

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

}); 
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

在此处输入图片说明

我在应用程序中测试了订阅回调被执行,但测试表明它没有。我在这里完全误解了整个单元测试概念吗?我究竟做错了什么?

编辑:

根据 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');
  });

});

});
Run Code Online (Sandbox Code Playgroud)

dmc*_*dle 6

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

我会通过尝试使用模拟来模拟TranslateService您的提供者数组中的来解决这个问题。也许是这样的(但模拟所有需要的方法):

class TranslateServiceStub {
    setDefaultLang(lang: string) { }
    use(lang: string) { }
    get onLangChange() { return of({lang: 'en'}) }
}
Run Code Online (Sandbox Code Playgroud)

并在您的提供者数组中更改为 TestBed

TranslateService,
Run Code Online (Sandbox Code Playgroud)

{ provide: TranslateService, useClass: TranslateServiceStub },
Run Code Online (Sandbox Code Playgroud)

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

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');
  });
Run Code Online (Sandbox Code Playgroud)

不过,正如我在上面的评论中提到的,显然这是一项特别难以模拟的服务。

祝你好运。:)