角度7组件方法的单元测试

时间:2018-12-14 10:59:15

标签: angular unit-testing karma-jasmine angular7

我的组件代码-

import { Component, EventEmitter, Input, OnInit, OnChanges, SimpleChanges,  Output } from '@angular/core';
import { CI, CiWithStatus } from '../ci-list.service';
import { ContextPanelApi } from '../../../../../../../../shared/shared-html/js/directives/oprContextPanel/oprContextPanel/oprContextPanelApi.service';

@Component({
  selector: 'opr-watchlist-cards',
  templateUrl: './watchlist-cards.component.html',
  styleUrls: ['./watchlist-cards.component.scss']
})
export class WatchlistCardsComponent implements OnInit, OnChanges {

  @Input() ciList: CiWithStatus[];
  @Input() itemWidth: number;
  @Input() itemHeight: number;
  @Input() zoomLevel: number;

  @Output() onSelectedCisChanged: EventEmitter<CI[]> = new EventEmitter<CI[]>();

  private _selectedItems: CI[] = [];

  constructor(private _oprContextPanelApiService: ContextPanelApi) {
  }

  ngOnInit() {
    console.debug('ciList', this.ciList);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if(changes.zoomLevel) {
      this.zoomLevel = changes.zoomLevel.currentValue;
    }
  }

  onItemClick(event: MouseEvent, ci: CI) {
    if (event.ctrlKey) {
      if (this.isSelected(ci)) {
        this._selectedItems.splice(this._selectedItems.indexOf(ci), 1);
      } else {
        this._selectedItems.push(ci);
      }
    } else {
      this._selectedItems = [ci];
    }
    this.onSelectedCisChanged.emit(this._selectedItems);
  }

  onItemRightClick(event: MouseEvent, ci: CI) {
    const position = {left: event.clientX, top: event.clientY};
    const contextPanelConfig = {
      title: 'context menu dummy ' + ci.name,
      position
    };
    const contextPanelPages = [];
    this._oprContextPanelApiService.openContext(contextPanelConfig, contextPanelPages, () => {
    });
    return false; //prevent native browser context menu
  }

  isSelected(ci: CI) {
    return this._selectedItems.includes(ci);
  }
}

我的Spec文件代码-

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SimpleChange } from '@angular/core';
import { WatchlistCardsComponent } from './watchlist-cards.component';
import { AppSharedModule } from '../../../../../app-shared/src/lib/app-shared.module';
import { WatchlistCardComponent } from './watchlist-card/watchlist-card.component';
import { ContextPanelApi } from 'shared/directives/oprContextPanel/oprContextPanel/oprContextPanelApi.service';

export class MockContextPanelApi {

}

describe('WatchlistCardsComponent', () => {
  let component: WatchlistCardsComponent;
  let fixture: ComponentFixture<WatchlistCardsComponent>;
  let params;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [AppSharedModule],
      declarations: [WatchlistCardComponent, WatchlistCardsComponent],
      providers: [{ provide: ContextPanelApi, useClass: MockContextPanelApi }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(WatchlistCardsComponent);
    component = fixture.componentInstance;
    params = {
      ci: {
        global_id: "9e76bafea39c49e786360baeb2551fd7",
        icon: "/odb/icons/unix/unix_32.svg",
        id: "9e76bafea39c49e786360baeb2551fd7",
        last_changed: 1540465938749,
        long_id: "1;;9e76bafea39c49e786360baeb2551fd7",
        name: "srv0",
        status: 0,
        type: "unix",
        type_label: "Unix",
        event: "link"
      },
      event: {

      }
    };
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call ngOnChanges', () => {
    component.zoomLevel = 3;
    component.ngOnChanges({
      zoomLevel: new SimpleChange(null, component.zoomLevel, true)
    });
    fixture.detectChanges();
  })

  it('should call the onItemClick method', async(() => {
    spyOn(component, 'onItemClick');
    component.onItemClick(params.event, params.ci);
    fixture.whenStable().then(() => {
      expect(component.onItemClick).toHaveBeenCalled();
    });
  }));

  it('should call the onItemRightClick method', async(() => {
    spyOn(component, 'onItemRightClick');
    component.onItemRightClick(params.event, params.ci);
    expect(component.onItemRightClick).toHaveBeenCalled();
  }));

  it('should call the isSelected method', async(() => {
    spyOn(component, 'isSelected');
    component.isSelected(params.ci);
    expect(component.isSelected).toHaveBeenCalled();
  }));

});

我想介绍这些功能,我尝试在规范中进行此操作,但仍然说功能未涵盖。

请指导我如何介绍isSelected,onItemRightClick,onItemClick方法的功能和语句

谢谢。

1 个答案:

答案 0 :(得分:2)

原因是spyOn(),它将用存根替换原始方法。在Jasmine Doc for spy中读取有关内容。因此,当您致电component.onItemClick时。您只是在调用间谍而不是原始功能。因此没有代码覆盖。

修复:spyOn(component, 'onItemClick').and.callThrough();。文档中也对此进行了解释。

但是,IMO正在编写的测试不是很有用。例如:

 line 1:     component.onItemClick(params.event, params.ci);
             fixture.whenStable().then(() => {   
 line 2:    expect(component.onItemClick).toHaveBeenCalled();  

line 1-您正在手动呼叫onRightClick()。因为您是手动调用该函数,所以line 2将始终为true。但是,IRL会在右键单击HTML中的元素时触发此功能。

您应该做的是获取组件引用,例如(我尚未测试此代码,它只是一个引用,并且我假设您有一个具有onclick的element(button)):

let fixture: ComponentFixture<WatchlistCardsComponent>;    
const buttonEle: HTMLElement = fixture.nativeElement.querySelector('button');
spyOn(component, 'onItemClick');
button.click();
fixture.whenStable().then(() => {   
   expect(component.onItemClick).toHaveBeenCalled(); ...

这将在组件函数上创建一个间谍(与您所做的相同),不同之处在于您不是在手动调用onItemClick,而是buttonclick将自动触发函数调用,因此无需调用eventHandler手动。