【问题标题】:TypeError: Cannot read property 'elementRef' of undefinedTypeError:无法读取未定义的属性“elementRef”
【发布时间】:2021-05-05 17:02:36
【问题描述】:

我尝试运行单元测试用例,但它抛出错误消息 TypeError: Cannot read property 'elementRef' of undefined

list.component.ts

const elementHeader= this.listTable['elementRef'].nativeElement.querySelectorAll('.adf-datatable-header  > .adf-datatable-row')[0];
      elementHeader.classList.add("testCheck");
      let rowsList = this.listTable.rows;
      if(rowsList){
      for(let i=0;i<=rowsList.length;i++){
          if(i==0){
              const elementBody= this.listTable['elementRef'].nativeElement.querySelectorAll('.adf-datatable-body  > .adf-datatable-row')[0];
              elementBody.classList.add("testCheck");
          }
           
          const elementBody= this.listTable['elementRef'].nativeElement.querySelectorAll('.adf-datatable-body  > .adf-datatable-row')[i];
           if( rowsList[i].dtPurged && rowsList[i].dtPurged != null ){
               elementBody.classList.add("testCheck");
           }
       
        }

list.component.spec.ts

import { ElementRef, Injectable } from '@angular/core';
let h1: HTMLElement;
  let elRef: ElementRef;
 beforeEach(() => {
 h1 = component.listTable['elementRef'].nativeElement.querySelector('.adf-datatable-body  > .adf-datatable-row');
 });

请帮我解决这个问题

【问题讨论】:

    标签: angular typescript karma-jasmine


    【解决方案1】:

    在h1之前定义listTable:

    beforeEach(() => {
    component.listTable = // Define here
     h1 = component.listTable['elementRef'].nativeElement.querySelector('.adf-datatable-body  > .adf-datatable-row');
     });
    

    【讨论】:

    • 感谢您的回复 向 component.listTable 声明价值需要提供什么。请告诉我
    • 在 list.component.ts 中,复制 this.listTable 的值并在规范文件中使用它,在 component.listTable = /*that value*/。这应该做的工作。如果仍然遇到问题.. 请在问题中添加整个组件代码或在 stackblitz 上复制它,这样更容易检查?
    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2019-08-19
    • 1970-01-01
    相关资源
    最近更新 更多