首页 > 解决方案 > TypeError:无法读取未定义的属性“elementRef”

问题描述

我试图运行单元测试用例,但它抛出错误消息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');
 });

请帮我解决这个问题

标签: angulartypescriptkarma-jasmine

解决方案


在 h1 之前定义 listTable:

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

推荐阅读