角度:测试是否执行了EventEmitter订阅回调

时间:2018-12-21 11:39:12

标签: angular typescript unit-testing jasmine karma-jasmine

我已经像这样嘲笑了TranslateService:

import { EventEmitter } from '@angular/core';
import { LangChangeEvent } from '@ngx-translate/core';

export class MockTranslateService {
    onLangChange = new EventEmitter<LangChangeEvent>();
    setDefaultLang(lang: string) { }
    use(lang: string) {
        this.onLangChange.emit({lang: lang} as LangChangeEvent);
     }
}

这是我要测试的app.component的ngOnInit方法:

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

    this.translateService.onLangChange.subscribe((langChangeEvent: LangChangeEvent) => {
        this.localStorageService.setItem(LocalStorageService.languageKey, langChangeEvent.lang);
    });
}

这是我在app.component.spec.ts中为ngOnInit编写的测试,以检查ngOnInit是否将语言保存在本地存储中:

  describe('ngOnInit', () => {
  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);
    spyOn(localStorageService, 'setItem');
    spyOn(translateService.onLangChange, 'emit');
    component.ngOnInit();
    translateService.onLangChange.emit({lang: 'de'}); <----- Shouldn't this have triggered the subscription callback in the ngOnInit of the component?
    expect(translateService.onLangChange.emit).toHaveBeenCalled();
    fixture.detectChanges();

    expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
});

}); 

这是该测试的输出:

enter image description here

我不明白。如果我在测试中调用了EventEmitter的发射,那该不触发组件中的订阅吗?

1 个答案:

答案 0 :(得分:1)

问题是您创建了spy

spyOn(translateService.onLangChange, 'emit');

此间谍取代了原始的发射事件,该功能现在仅可用作间谍。您需要将其更改为:

spyOn(translateService.onLangChange, 'emit').and.callThrough();

以便emit的原始EventEmitter功能起作用。