类型“ DebugElement”上不存在属性“ click”

时间:2019-06-08 19:47:19

标签: angular typescript jasmine karma-jasmine angular-cli-v7

我刚开始接触业力和茉莉花。我被困在无法对组件执行单元测试的位置,我要触发的功能是通过按钮的*ngIf条件绑定某些特定值。

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

从终端使用ng test运行我的规范文件时,它没有启动就抛出错误like this error TS2339: Property 'click' does not exist on type 'DebugElement'。 但是,当我更改规格文件中的某些内容并将其保存时,ng test会自动运行规格文件并显示此错误-TypeError: Cannot read property 'nativeElement' of nullTypeError: Cannot read property 'nativeElement' of null

因此,简而言之,我无法以html文件中的定位标记为目标来触发组件中的lookBack函数。我不确定自己在做什么错。到目前为止,我已经根据搜索和阅读来格式化了代码。

任何帮助将不胜感激。谢谢:)

2 个答案:

答案 0 :(得分:1)

您可以像这样使用JavaScript选择器

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

答案 1 :(得分:0)

如果href标记对使用并不重要,则可以使用button代替标记

但是如果需要使用它,可以尝试一下

<a href="" ng-click="logout()">Sign out</a>

但是这会重新加载页面,只是在方法中使用了阻止默认值