【问题标题】:Property 'click' does not exist on type 'DebugElement'“DebugElement”类型上不存在属性“click”
【发布时间】:2019-10-23 20:45:46
【问题描述】:

我刚刚开始使用 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 null 和 TypeError: Cannot read property 'nativeElement' of null

所以,简而言之,我无法定位 html 文件中的锚标记来触发组件中的回溯功能。我不确定我做错了什么。到目前为止,我已经根据我的搜索和阅读对代码进行了格式化。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 现在 ng 测试每次都运行良好,但越来越早 - 失败:未捕获(承诺中):TypeError:无法读取 null 的属性“点击” TypeError:无法读取 null 的属性“点击”跨度>
    • 你确定你的ngIf不是假的吗?
    • @vivkv 我可以看到component.variableX = 'value1'; 和*ngIf="(variableX !== 'value1') 所以肯定a 不存在
    • 很高兴它有帮助,问候
    【解决方案2】:

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

    但如果需要使用不如试试这个

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

    但是这个重新加载你的页面只是在方法中使用防止默认值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-09
      • 2021-07-10
      • 2017-07-22
      • 2023-03-26
      • 2023-04-02
      • 2019-12-20
      • 2021-12-07
      相关资源
      最近更新 更多