Search code examples
angulartypescriptjasminekarma-jasmineangular-cli-v7

Property 'click' does not exist on type 'DebugElement'


I have just started with Karma and Jasmine. I am stuck at a point where I am not able to perform a unit test on my component, the function that I want to trigger is in binding with *ngIf condition with the button for some specific values.

my.component.ts

import { Component, Input, EventEmitter, Output } from '@angular/core';
import { Location } from '@angular/common';
import { XService } from 'src/app/services/x-service';

@Component({
  selector: 'my-head-component',
  templateUrl: './headComponent.html',
  styleUrls: ['./head.scss']
})
export class MyComponent {
  @Input() variableX = '';

  @Output() outVar1: EventEmitter<string> = new EventEmitter();
  @Output() outVar2: EventEmitter<string> = new EventEmitter();

  y1='';
  y2='';
  constructor(private location: Location,
    private xServ:XService ) { }

  lookBack() {
    this.location.back();
  }

  doSearch() {
    this.y1= '';
    this.y2 = '';

    this.outVar1.emit(this.y1);
    this.outVar2.emit(this.y2);
  }

   ...
}

headComponent.html

...

<header class="head">
    <div class="firstDiv">
        <a href="javascript:;" class="btnClass"
          *ngIf="(variableX !== 'value1')
              && (variableX !== 'value2')
          (click)="lookBack()">
        </a>
    </div>
</header>

...

x-service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Yserv } from './y-service';
import { Router } from '@angular/router';

const keyName = 'xxxxx';

@Injectable({
  providedIn: 'root'
})
export class XService {

  constructor(private http: HttpClient, private util: YServ,
    private router: Router) { }

  logout() {
    this.router.navigate(['/home-page']);
    this.util.removeValue(keyName);
  }

  getUser() {
    return JSON.parse(this.util.getValue(keyName));
  }

}

my.component.spec.ts

import {TestBed, ComponentFixture, inject, async} from '@angular/core/testing';
import {MyComponent} from './my.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { XService } from 'src/app/services/x-service';
import {Location, LocationStrategy, PathLocationStrategy, APP_BASE_HREF} from '@angular/common';
import { FormsModule } from '@angular/forms';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';

describe('MyComponent',()=>{

  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let xServ: XService;
  let locServ : Location;
  let backEl: DebugElement;

  beforeEach(async(()=>{
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [FormsModule, HttpClientTestingModule,RouterTestingModule],
      providers: [XService,Location,{ provide: LocationStrategy, useClass: PathLocationStrategy }, {provide: APP_BASE_HREF, useValue : '/' }]
    }).compileComponents().then(()=>{
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        xServ = TestBed.get(XService);
        locServ = TestBed.get(Location);
    });
  }));

  it('should have a defined a type of MyComponent', () => {
    expect(component).toBeTruthy();
  });

  it('should click back button when variableX = value1 or value2 or value3 and call function Back()',async(()=>{
    spyOn(locServ,'back');
    component.variableX = 'value1';
    fixture.detectChanges();
    fixture.whenStable().then(()=>{
      backEl = fixture.debugElement.query(By.css('a.btnClass')).nativeElement;
      backEl.click();   /* <- error TS2339: Property 'click' does not exist on type 'DebugElement'. */
      expect(locServ.back).toHaveBeenCalled();
    });
  }));
});

While running my spec file using ng test from the terminal, it's not starting it is throwing an error like this error TS2339: Property 'click' does not exist on type 'DebugElement'. But as I change something in my spec file and save it, ng test automatically runs my spec file and shows this error- TypeError: Cannot read property 'nativeElement' of null and TypeError: Cannot read property 'nativeElement' of null

So, In a nutshell, I am not able to target the anchor tag in the html file to fire lookBack function in my component. I am not sure what I am doing wrong. So far I have formatted the code based upon my searches and reading.

Any help would be highly appreciated. Thanks :)


Solution

  • You can use JavaScript selector like this

    const button = fixture.debugElement.nativeElement.querySelector('.btnClass');
    button.click();