茉莉花测试失败:预期已调用间谍openQuickSubtypes。上下文菜单测试cas

时间:2020-02-21 10:39:11

标签: angular typescript karma-jasmine testcase angular-cdk

我在进行茉莉花测试时出错,已调用预期的间谍openQuickSubtypes

我已经实现了上下文菜单。

component.html

<div class="each-shift" *ngFor="let shift of shiftsWithEmptyBoxes">
    <div class="shift-cover" [ngClass]="shiftDetails(shift)">
      <div class="requested-vertical-bar"
           [ngClass]="getShiftVerticalBarColor(shift)"></div>
      <div class="shift-left-box" #subtype (contextmenu)="openQuickSubtypes(subtype, subtypeMenu, shift); $event.preventDefault();">
        {{ showShiftOverTime(shift) }}
        {{ getShiftSubTypeLetter(shift, false) }}
        {{ showSubTypeShiftNotation(shift) }}
      </div>

component.ts

 openQuickSubtypes(origin:any,menu:any,index:number)
  {
    this.contextService.openContextMenu(origin,menu,this.viewContainerRef,{data:index})
    .subscribe(openMenu=>{
    })
  }

我的测试用例:测试用例应右键单击

it('should right click', fakeAsync(() => {
    component.shiftsWithEmptyBoxes = [{
      "shiftId": 130374,
      "shiftType": "empty"
    }
    ];
    fixture.detectChanges();
    const menuClick = fixture.debugElement.query(By.css('.shift-left-box'));
    const spyonOpenQuickSubtypes = spyOn(component, 'openQuickSubtypes').and.callThrough();
    const event = new MouseEvent('click',
    {
    view: window,
    bubbles: true,
    cancelable: true,
    relatedTarget: document
    });  
    menuClick.nativeElement.dispatchEvent(event);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(spyonOpenQuickSubtypes).toHaveBeenCalled();
    });
  }));

每当我运行测试用例时,都会出现以下错误:

错误:预期已调用间谍openQuickSubtypes。

1 个答案:

答案 0 :(得分:1)

尝试这种方法,不要使用spyOn的返回值


it('should right click', fakeAsync(() => {
    component.shiftsWithEmptyBoxes = [{
      "shiftId": 130374,
      "shiftType": "empty"
    }
    ];
    fixture.detectChanges();
    const menuClick = fixture.debugElement.query(By.css('.shift-left-box'));
    spyOn(component, 'openQuickSubtypes').and.callThrough();
    menuClick.triggerEventHandler("contextmenu", new  MouseEvent("contextmenu"));
    fixture.detectChanges();
    expect(component.openQuickSubtypes).toHaveBeenCalled(); 
  }));