簡體   English   中英

組合組件的單元測試

[英]Unit test of combo component

我已經在angular2中編寫了一個compo組件並為其編寫了單元測試代碼。由於我是初學者,因此我無法測試創建的組件。因此,請為此提供幫助。

import { Component, Input, Output, EventEmitter } from "@angular/core";
import { ComboInterface } from './ComboInterface';

@Component({
  moduleId: module.id,
  selector: 'combo-compo',
  template: `
      <select name="theme" class="form-control" [ngModel]="selectedObject" (ngModelChange)="onChangeObj($event)">
        <option [ngValue]="theme" *ngFor="let theme of dataObject" >{{theme.value}}</option>
      </select>
            `
})

export class ComboComponent {
  selectedObject: ComboInterface;
  @Input() dataObject: Array<ComboInterface>;
  @Output() onComboChange = new EventEmitter();

  onChangeObj(newObj: ComboInterface) {
    this.selectedObject = newObj;
    this.onComboChange.emit(this.selectedObject);
  }

}

我已經為下面的代碼編寫了單元測試代碼

describe('ComboComponent Unit Test', () => {
    let comp: ComboComponent;
    let fixture: ComponentFixture<ComboComponent>;
    let de: DebugElement;
    let el: HTMLElement;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ComboComponent], // declare the test component
            imports: [ReactiveFormsModule, FormsModule]
        });
        fixture = TestBed.createComponent(ComboComponent);
        comp = fixture.componentInstance;

    });

    it('should create ComboComponent', () => expect(comp).toBeDefined());

    it('should create a ComboComponent with values', () => {
        comp.dataObject = [
            {
                'value': 'Victoria Cantrell test',
                'key': '0839',
            }, {
                'value': 'Pearl Crosby Test',
                'key': '8262'
            }, {
                'value': 'Colette Foley Test',
                'key': '8968'
            }
        ];
                comp.onChangeObj(comp.dataObject[0]);
    });

});

通過運行npm test ,代碼可以正常運行,但是如何測試創建的組件?

測試使用斷言。 您可以使用expect進行斷言。

例如,您希望組件發出一個值,對嗎?

所以oyu必須對它進行監視 :為了簡單起見,間諜是一種可以監視您的函數是否被調用的東西

測試示例是:

it('onChangeObj should emit an event', () => {
    comp.dataObject = [/* data */];
    let spy = spyOn(component.onComboChange, 'emit');
    comp.onChangeObj(/* anything you want, even null */);
    expect(spy).toHaveBeenCalled();
});

這只是測試的一部分。 請在expect()上查看IDE的自動完成功能,以了解您可以執行的操作,然后您將對如何進行測試有個好主意!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM