调用方法的简单点击处理程序:SPEC HAS NO EXPECTATIONS

Simple click handler to call method: SPEC HAS NO EXPECTATIONS

Angular 应用程序 运行 Jasmine on Karma 用于单元测试。我提供了一个测试,看看是否在点击事件上调用了该方法。

结果:SPEC 没有预期应在单击视图项时调用方法

为什么我没有预期间谍(方法)已被调用?

HTML

<h3 class="general-log-heading">
    <a class="btn btn-link onViewItemClick" (click)="onViewItem(searchResultItem)">test</a>
</h3>

.TS

public onViewItem(item: Results): void {
  //method logic here
}

.spec(测试)

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SearchResultItemComponent } from './search-result-item.component';

let component: SearchResultItemComponent;
let fixture: ComponentFixture<SearchResultItemComponent>;

fdescribe('SearchResultItemComponent', () => {


    beforeEach(() => {
        
        TestBed.configureTestingModule({
            declarations: [],
            imports: [RouterTestingModule, HttpClientTestingModule],
            providers: []
        }).compileComponents();
        fixture = TestBed.createComponent(SearchResultItemComponent);
        component = fixture.componentInstance;
    });



    it('should call method on view item click', () => {
    fixture.detectChanges();
    const button = fixture.debugElement.query(By.css('.onViewItemClick'));
    const spy = spyOn(component, 'onViewItem');

    button.triggerEventHandler('click', null);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        expect(spy).toHaveBeenCalled();
    });
    
});
})

更新到 .spec 也尝试过

it('should should trigger a method on view item click', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      let comp = fixture.componentInstance;
      const spy = spyOn(comp, 'onViewItem');
  
      let el = fixture.debugElement.query(By.css('.onViewItemClick')).nativeElement.click();
      fixture.detectChanges();
      expect(spy).toHaveBeenCalled();
    });
  });


it('should should trigger a method on view item click', () => {
    fixture.detectChanges();

      let comp = fixture.componentInstance;
      const spy = spyOn(comp, 'onViewItem');
  
      let el = fixture.debugElement.query(By.css('.onViewItemClick')).nativeElement.click();
      fixture.detectChanges();
      expect(spy).toHaveBeenCalled();

  });

detectChanges 被急切评估,无需等待 whenStable

fixture.detectChanges();
expect(spy).toHaveBeenCalled();

另外,如果你想进行异步测试,你可以return你想要的承诺,或者你可以使用异步等待

fixture.detectChanges();
return fixture.whenStable().then(() => {
   expect(spy).toHaveBeenCalled();
});

fixture.detectChanges();
await fixture.whenStable();
expect(spy).toHaveBeenCalled();