属性 'click' 在类型 'DebugElement' 上不存在

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

我刚刚开始使用 Karma 和 Jasmine。我被困在无法对我的组件执行单元测试的地步,我想触发的功能与 *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 文件中的锚标记作为目标来触发组件中的回溯功能。我不确定我做错了什么。到目前为止,我已经根据我的搜索和阅读对代码进行了格式化。

如有任何帮助,我们将不胜感激。谢谢:)

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

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

如果使用 href 标签不重要,可以使用按钮代替标签

但如果需要使用它,请试试这个

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

但是重新加载您的页面只是在方法中使用阻止默认值