【问题标题】:Child Component with EventEmitter test带有 EventEmitter 测试的子组件
【发布时间】:2021-01-18 18:36:13
【问题描述】:

当样式更改为父组件时,我有这个子组件会发出 true 或 false:

export class PruebaComponent implements OnInit, OnChanges {

  @Output() statusEvent = new EventEmitter<boolean>();
  
  getSytle(): string {
     return this.valueStyle;
  }

  private calcStyle(): void {
     this.calcPopUpStyle();
     if (this.isEngReady) {
       this.valueStyle = 'icon-green';
       this.statusEvent .emit(true);
     } else {
       this.valueStyle = 'icon-red';
       this.statusEvent.emit(false);
     }
     this.ref.detectChanges();
   }
} 

我尝试编写测试以检查当 isEngReady 也为真时发出的 statusEvent 是否为真,我尝试了这个:

describe('PruebaComponent', () => {
   beforeEach(async(() => {
      TestBed.configureTestingModule({
       declarations: [ChatComponent]})
    .compileComponents();
    }));

   it('should emit chat availability to true if the engagement is available', () => {
     spyOn(component.statusEvent, 'emit')
     component.isEngReady = true;
     component.getSytle();
     //expect(component.statusEvent.emit).toHaveBeenCalled();
     expect(component.statusEvent.emit).toHaveBeenCalledWith(true);
   });
});

但我收到此错误消息: 预期的间谍发射已被调用:[真] 但它从未被调用过。

【问题讨论】:

    标签: angular typescript testing eventemitter testunit


    【解决方案1】:

    你应该改变你的间谍功能 spyOn(component.chatAvailableEvent, 'emit')spyOn(component.statusEvent, 'emit')

    describe('PruebaComponent', () => {
       beforeEach(async(() => {
          TestBed.configureTestingModule({
           declarations: [ChatComponent]})
        .compileComponents();
        }));
    
       it('should emit chat availability to true if the engagement is available', () => {
         // given
         const statusSpy = spyOn(component.statusEvent, 'emit')
         component.isEngReady = true;
    
         // when
         component.calcStyle() // <-- call here the function or action that trigger this private function.
         // or make it public // I don't recommend that. But it can be.
    
         // expect
         expect(statusSpy).toHaveBeenCalledWith(true);
       });
    });
    

    【讨论】:

    • 它有效,我调用了错误的方法并使用了错误的变量事件。非常感谢。我让代码解决方案在这里,所以也许可以帮助其他人。 it('如果参与可用,则应将聊天可用性设为 true', () => { const spy = spyOn(component.statusEvent, 'emit'); component.isEngReady = true; component.checkAvailability(); expect(spy ).toHaveBeenCalledWith(true); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 2018-10-07
    • 1970-01-01
    • 2018-01-30
    • 2021-07-26
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多