Getting Cannot read properties of undefined (reading 'style') in Karma console

Viewed 16

Html file

<div [id]="solutionData?.conceptualArchitecture.title" class="pointerList concep-container">
      <div class="col-md-12 pl-0">
        <p
          class="concepTitle"
          [innerHTML]="solutionData?.conceptualArchitecture.title"
        ></p>
      </div>
      <div class="col-md-12 pl-0">
        <div
          *ngFor="
            let data of solutionData?.conceptualArchitecture.submenuDetails;
            let i = index
          "
          [ngClass]="i == 0 ? 'architectSlides-active' : ''"
          class="architectSlides"
        >
          <div style="background: #f3f4f8 0% 0% no-repeat padding-box">
            <div class="col-md-12 pl-0 concepHeadingWrapper">
              <div class="col-md-3 pl-0 flex-column concepHeadingWrapper-1">
                <div
                  *ngIf="data?.submenuDetails.heading"
                  class="concepHeading"
                  [innerHTML]="data?.submenuDetails.heading"
                ></div>
                <div
                  *ngIf="data?.submenuDetails.description"
                  class="concepDescr"
                  [innerHTML]="data.submenuDetails.description"
                >
                   
                </div>
    
                <div *ngIf="data?.submenuDetails.legends">
                  <app-do-legends
                    *ngFor="let legend of data.submenuDetails.legends"
                    [legendName]="legend.name"
                    [legendIconUrl]="legend.iconUrl"
                  ></app-do-legends>
                </div>
              </div>
              <div class="col-md-9 concepImg">
                <img
                  [src]="data?.submenuDetails.imageUrl"
                  style="width: 89%; margin: 0 auto"
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-12 concepWrapper">
        <button class="concepCarouselBtn" (click)="carousel()">&#10094;</button>
        <span style="padding: 0.625rem" class="slideNo">{{
          "1/" + solutionData?.conceptualArchitecture.submenuDetails.length
        }}</span>
        <button
          class="concepCarouselBtn"
          style="transform: rotate(180deg)"
          (click)="carousel()"
        >
          &#10094;
        </button>
      </div>
    </div>

ts file

import { Component, OnInit } from '@angular/core';
import { APP_CONST } from 'src/app/app-const';
import { ApiService } from 'src/app/services/api.service';
import { DigitalOperationDataService } from 'src/app/services/digital-operation-data.service';

@Component({
  selector: 'app-do-solution',
  templateUrl: './do-solution.component.html',
  styleUrls: ['./do-solution.component.scss'],
})
export class DoSolutionComponent implements OnInit {
  slideIndex = 0;
  solutionData: any;

  navigation: Array<{ id: string; Title: string }>;
  isContacts: any;
  contactData: any;

  constructor(
    private doApiService: DigitalOperationDataService,
    private apiService: ApiService
  ) {}

  ngOnInit(): void {
    this.getSolutionData();
    this.getContactData();
  }

  ngAfterViewInit() {
    this.carousel();
    // this.stickyecondaryNav();
  }

  // tab function
  scrollTo(e: any) {
    //console.log(e);
    let el = document.getElementById(e);
    //console.log(el);
    if (el) el.scrollIntoView();
  }

  carousel() {
    var i;
    let x = document.getElementsByClassName(
      'architectSlides'
    ) as HTMLCollectionOf<HTMLElement>;
    console.log(x);
    for (i = 0; i < x.length; i++) {
      x[i]!.style.display = 'none';
    }
    this.slideIndex++;
    if (this.slideIndex > x.length) {
      this.slideIndex = 1;
    }
    x[this.slideIndex - 1]!.style.display = 'block';
    console.log('inside carousel');
    /* setTimeout(carousel, 2000); */
    var slide = document.getElementsByClassName(
      'slideNo'
    ) as HTMLCollectionOf<HTMLElement>;
    slide[0].innerText = `${this.slideIndex}/${this.solutionData?.conceptualArchitecture.submenuDetails.length}`;
    console.log(this.slideIndex + '/2');
  }

  openTab(evt: any, tabNumber: number) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName(
      'tabcontent'
    ) as HTMLCollectionOf<HTMLElement>;
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i]!.style.display = 'none';
    }
    tablinks = document.getElementsByClassName('tablinks');
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(' active', '');
    }
    let name = document.getElementById(`${tabNumber}`);
    name!.style.display = 'flex';
    evt.currentTarget.className += ' active';
  }

  getSolutionData() {
    let legends: any[] = [];
    let legendsConArch: { name: any; iconUrl: any }[] = [];
    let conceptualArchSubMenuData: {
      // title: el.Title.split('_')[0],
      submenuDetails: {
        heading: any;
        description: any;
        imageUrl: any;
        legends: { name: any; iconUrl: any }[];
      };
    }[] = [];
    let modulesSubMenuData: { title: any; description: any; image: any }[] = [];
    this.doApiService.getSolDimensions().subscribe((res) => {
      res[0].legends.forEach((el: any) => {
        legends.push({
          name: el.Name.split('_')[1],
          iconUrl: el.Icon[0].url,
        });
      });
    });

    this.doApiService.getSolConArch().subscribe((res) => {
      res.forEach((el: any, i: string | number) => {
        el.legends.forEach((ele: any) => {
          legendsConArch.push({
            name: ele.Name.split('_')[1],
            iconUrl: ele.Icon[0].url,
          });
        });
      });
    });
    this.doApiService.getSolutionData().subscribe((res) => {
      /* CONCEPTAL ARCHITECTURE SUBMENU DATA */
      res.do_solution_conceptual_architecture_sub_menus.forEach((el: any) => {
        console.log(el);
        conceptualArchSubMenuData.push({
          // title: el.Title.split('_')[0],
          submenuDetails: {
            heading: el.Heading.split('_')[1],
            description: el.Description,
            imageUrl: el.Image[0].url,
            legends: legendsConArch,
          },
        });
      });

      /* MODULES SUBMENU DATA */
      res.do_solution_module_sub_menus.forEach((ele: any) => {
        modulesSubMenuData.push({
          title: ele.Title,
          description: ele.Description,
          image: ele.Image[0].url,
        });
      });

      this.solutionData = {
        title: res.Title,
        dimensions: {
          title: res.do_solution_dimensions[0].Title,
          heading: res.do_solution_dimensions[0].Heading,
          description: res.do_solution_dimensions[0].Description,
          imageUrl: res.do_solution_dimensions[0].Image[0].url,
          legends: legends,
        },
        conceptualArchitecture: {
          title: res.do_solution_conceptual_architectures[0].Title,
          submenuDetails: conceptualArchSubMenuData,
        },
        module: {
          title: res.do_solution_modules[0].Title,
          heading: res.do_solution_modules[0].Heading,
          description: res.do_solution_modules[0].Description,
          submenuDetails: modulesSubMenuData,
        },
        demo: {
          title: res.do_solution_demos[0].Title,
          description: res.do_solution_demos[0].Description,
          videoLink: res.do_solution_demos[0].Video_link,
          videoImage: res.do_solution_demos[0].Video_image[0].url,
          linkText: res.do_solution_demos[0].Link_text,
          linkUrl: res.do_solution_demos[0].Link_url,
        },
      };

      /* NAVIGATION TITILE*/
      this.navigation = [
        { id: '01', Title: res.do_solution_dimensions[0].Title },
        { id: '02', Title: res.do_solution_conceptual_architectures[0].Title },
        { id: '03', Title: res.do_solution_modules[0].Title },
        { id: '04', Title: res.do_solution_demos[0].Title },
      ];
    });
  }

  getContactData() {
    this.apiService.getContactData(APP_CONST.API.contacts).subscribe((res) => {
      if (res) {
        for (let i = 0; i < res.length; i++) {
          if (res[i].Title == 'Digital operations') {
            this.isContacts = true;
            this.contactData = res[i];
          }
        }
      }
      console.log(this.contactData);
    });
  }
}

spec file

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { DoSolutionComponent } from './do-solution.component';

fdescribe('DoSolutionComponent', () => {
  let component: DoSolutionComponent;
  let fixture: ComponentFixture<DoSolutionComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [ DoSolutionComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DoSolutionComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('should call getSolutionData() on init method',()=>{
    spyOn(component,'getSolutionData').and.callThrough();
    component.ngOnInit();
    expect(component.getSolutionData).toHaveBeenCalled();
  });
  it('should call getContactData() on init method',()=>{
    spyOn(component,'getContactData').and.callThrough();
    component.ngOnInit();
    expect(component.getContactData).toHaveBeenCalled();
  });
  it('should call carousel() on ngAfterViewInit method',()=>{
    spyOn(component,'carousel').and.callThrough();
    component.ngAfterViewInit();
    const x = fixture.debugElement.query(By.css('.architectSlides'));
    expect(component.carousel).toHaveBeenCalled();
  });
});

While running the test case getting reading this error undefined Cannot read properties of undefined (reading 'style') using the correct selector then also getting style of undefined.The very first test case is getting failer and its giving the error inside the carousel() function at x[this.slideIndex - 1]!.style.display = 'block'; not getting what is the bug in the code

0 Answers
Related