1

我刚刚开始使用 Karma 和 Jasmine。我被困在无法对组件执行单元测试的地步,我想要触发的功能*ngIf与某些特定值的按钮的条件绑定。

我的.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);
  }

   ...
}

头组件.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));
  }

}

我的.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的错误。但是当我更改我的规范文件中的某些内容并保存它时,ng test 会自动运行我的规范文件并显示此错误- 并且 error TS2339: Property 'click' does not exist on type 'DebugElement'TypeError: Cannot read property 'nativeElement' of nullTypeError: Cannot read property 'nativeElement' of null

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

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

4

2 回答 2

3

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

const button = fixture.debugElement.nativeElement.querySelector('.btnClass');
button.click();
于 2019-06-08T19:56:23.463 回答
0

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

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

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

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

于 2019-06-09T03:13:57.420 回答