【问题标题】:How to Unit test the @viewChild ElementRef angular如何对@viewChild ElementRef 角度进行单元测试
【发布时间】:2021-03-11 04:32:00
【问题描述】:

我的组件文件有以下代码

@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();
     });
  });

我读到了这个How to mock a nativeElement.focus() in Angular 4 spec file

但是,我仍然无法将其设为绿色。

  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');
      });
     });

【问题讨论】:

    标签: angular typescript viewchild angular-unit-test


    【解决方案1】:

    您似乎有几个问题。

    你的第一个错误

    TypeError:无法读取未定义错误属性的属性“管道”

    是因为您没有正确实例化您的pickupClusterPointsService 服务。

    第二个错误

    TypeError: 无法设置属性 'borderLeft' of undefined at

    我还不确定

    【讨论】:

    • 是的,你是对的。我得到了它。将更新我的代码。
    • 我需要一些帮助来对此pastebin.pl/view/08e0f7ca进行单元测试
    • 您好,如果您在 stackblitz 中使用此代码创建一个新帖子,然后私信我,我可以看看。
    • 嗨 Lucho 我无法在 stackblitz 创建它。它是应用程序的一部分,应用程序是巨大的。但是,如果您查看代码,它与当前问题中的上述代码几乎相同。 card 是 HTMLElement 元素。在新代码中,我不想为卡片应用边框(卡片是 div)。我想将边框应用于 div 内的角度组件。
    • 我正在使用这一行pickupClusterCard = card.querySelector('.pnd-BaseStopCard');要获取角度分量(
    猜你喜欢
    • 2021-05-07
    • 2019-05-15
    • 2020-06-12
    • 2020-07-10
    • 2019-11-27
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多