簡體   English   中英

如何對@viewChild ElementRef angular 進行單元測試

[英]How to Unit test the @viewChild ElementRef angular

我的組件文件有以下代碼

@ViewChild('clusterCard', { static: false }) clusterCard: ElementRef;



highLightTheClusterCard(point: PickupClusterPoint) {
    if (point) {
      const card: HTMLElement = _get(this.clusterCard, 'nativeElement');
      const selectedPoint: PositioningPoint = this.lane.data.selectedPostioningPoint;

      /* if card is available, position point of the card and the cluster is same and infowindow over the cluster is open then
         highlight the card */
      if (card && _isEqual(point.pointData, selectedPoint) && point.openInfoWindow) {
        card.scrollIntoView();
        card['style'].borderLeft = `5px solid ${this.lane.data.color || 'transparent'}`;
      } else {
        card['style'].borderLeft = `5px solid transparent`;
      }
    }
  }

  ngAfterViewChecked(): void {
    ...some code

    this.pickupClusterPointsService.positioningPoint$
      .pipe(skip(1), takeUntil(this.unsubscriber.done))
      .subscribe((point: PickupClusterPoint) => {
        this.highLightTheClusterCard(point);
      });
  }

HTML 文件

    <div #clusterCard>
      <pickup-cluster-stop-card
       ..some code
      >
      </pickup-cluster-stop-card>
    </div>

我想對 highLightTheClusterCard 方法進行單元測試。 我正進入(狀態

TypeError:無法讀取未定義錯誤屬性的屬性“管道”

和 TypeError:無法設置未定義的屬性“borderLeft”

單元測試文件

  beforeEach(() => {
   
     ...some code

    fixture = TestBed.createComponent(RouteLaneComponent);
    component = fixture.componentInstance;

    ....some code

    fixture.detectChanges();
  });

  fdescribe('highLightTheClusterCard', () => {
     it('should expect cluster card to be defined ', () => {
        // component.clusterCard.nativeElement = new HTMLElement();
        component.clusterCard = new ElementRef({ nativeElement: jasmine.createSpyObj('nativeElement', ['scrollIntoView', 'style'])});
        component.highLightTheClusterCard({ pointData: new PositioningPoint(), openInfoWindow: true} as PickupClusterPoint);
        // expect(component.clusterCard).toBeDefined();
         // expect(component.clusterCard.nativeElement.scrollIntoView).toHaveBeenCalled();
     });
  });

我讀了這篇如何在 Angular 4 規范文件中模擬 nativeElement.focus()

但是,我仍然無法將其變為綠色。

  MockService(PickupClusterPointsService, {
          ...more code
          positioningPoint$: of(undefined),
        }),  

解決方案:我在模擬服務中添加了positioningPoint$: of(undefined) MockService 在 Provider 內部。 你可以看到上面的行。

describe('highLightTheClusterCard', () => {
        it('should expect cluster card to be highlighted when hover over infowindow ', () => {
            component.lane.data.selectedPostioningPoint = new PositioningPoint();
            component.lane.data.color = '#2196F3';
            component.clusterCard = {
              nativeElement: jasmine.createSpyObj('nativeElement', ['scrollIntoView', 'style'])
            };
    
           component.highLightTheClusterCard({ pointData: new PositioningPoint(), openInfoWindow: true} as PickupClusterPoint);
    
           expect(component.clusterCard).toBeDefined();
           expect(component.clusterCard.nativeElement.scrollIntoView).toHaveBeenCalled();
           expect(component.clusterCard.nativeElement.style.borderLeft).toBe('5px solid #2196F3');
        });
        it('should expect cluster card not to be highlighted when hover out from the infowindow', () => {
          component.lane.data.selectedPostioningPoint = new PositioningPoint();
          component.clusterCard = {
            nativeElement: jasmine.createSpyObj('nativeElement', ['scrollIntoView', 'style'])
          };
         component.highLightTheClusterCard({ pointData: new PositioningPoint(), openInfoWindow: false} as PickupClusterPoint);
    
         expect(component.clusterCard).toBeDefined();
         expect(component.clusterCard.nativeElement.style.borderLeft).toBe('5px solid transparent');
      });
     });

你似乎有幾個問題。

你的第一個錯誤

TypeError:無法讀取未定義錯誤屬性的屬性“管道”

來自您沒有正確實例化您的pickupClusterPointsService 服務。

第二個錯誤

TypeError:無法設置未定義的屬性“borderLeft”

我還不確定

您已經使用“樣式”創建了您的間諜作為原生元素的 function

jasmine.createSpyObj('nativeElement', ['scrollIntoView', 'style'])

而不是財產

jasmine.createSpyObj('nativeElement', ['scrollIntoView'], {style: {}])

因此TypeError: Cannot set property 'borderLeft' of undefined是因為在card['style'].borderLeft中, card['style']不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM