预期间谍 toggleStyle 在调用函数时被调用

我正在使用茉莉花测试。


我有这个功能:


 style: string;

 toggleStyle(style: string, version: string) {

    this.style = `mapbox://styles/mapbox/${style}-${version}`;

  }


和模板:


 <div class="map-menu-item" (click)="toggleStyle('outdoors', 'v11')" [state]="[true]" menuItemToggle>

        <span>

          <fa-icon [icon]="faMountain" size="sm" class="pr-2"></fa-icon>Outdoors

        </span>

      </div>

所以我有这个单元测试功能:


 fit('Should mapbox style when user click on icon', () => {

    spyOn(component, 'toggleStyle').and.callThrough();

    fixture.debugElement.query(By.css('.map-menu-item')).nativeElement.click();

    fixture.detectChanges();

    expect(component.toggleStyle).toHaveBeenCalled();

  });

所以我调用函数:toggleStyle


但我仍然收到此错误:


Expected spy toggleStyle to have been called.

当然,我用谷歌搜索了这个错误。但是我做了一个 callThrough 并调用了函数。


那么我必须改变什么?


偶然的你
浏览 117回答 1
1回答

潇潇雨雨

选择器选择它匹配的第一个元素,所以你的选择器匹配这个元素:<div class="map-menu-item" (click)="toggleLayer('amsterdam')" [state]="[true]" menuItemToggle>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <fa-icon [icon]="faVideo" size="sm" class="pr-2"></fa-icon>CityHeat&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>单击处理程序调用的位置toggleLayer。将您的 HTML 更改为更具体:<div class="d-flex flex-column justify-content-start map-menu somethingMoreSpecific">&nbsp; &nbsp; &nbsp; <span class="map-menu-header">Layer</span>&nbsp; &nbsp; &nbsp; <div class="map-menu-item" (click)="toggleStyle('light', 'v10')" [state]="[true]" menuItemToggle>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <fa-icon [icon]="faAdjust" size="sm" flip="horizontal" class="pr-2"></fa-icon>Light&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; <div class="map-menu-item" (click)="toggleStyle('outdoors', 'v11')" [state]="[true]" menuItemToggle>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <fa-icon [icon]="faMountain" size="sm" class="pr-2"></fa-icon>Outdoors&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <div class="map-menu-item" (click)="toggleStyle('satellite', 'v9')" [state]="[true]" menuItemToggle>&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <fa-icon [icon]="faSatellite" size="sm" class="pr-2"></fa-icon>Satellite&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>fit('Should mapbox style when user click on icon', () => {&nbsp; &nbsp; spyOn(component, 'toggleStyle').and.callThrough();&nbsp; &nbsp; fixture.debugElement.query(By.css('.somethingMoreSpecific .map-menu-item')).nativeElement.click(); // change the selector to select the correct div&nbsp; &nbsp; fixture.detectChanges();&nbsp; &nbsp; expect(component.toggleStyle).toHaveBeenCalled();&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript