2017-06-20 84 views
0

我已經在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運行良好,但我如何測試組件創建??

回答

1

測試使用斷言。您使用expect作出斷言。

例如,你期望你的組件發出一個值,對吧?

所以奧尤必須把間諜它:使它容易,間諜是事端,將窺視你的函數,看它是否就是所謂的

的試驗例是:

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的自動完成,看看你可以用它做什麼,你會在如何測試之後做一個好主意!

+0

但是數據沒有顯示在組合組件中? – Keshav

+0

顯示的數據是端到端測試。在這裏,你是單元測試。你必須測試你的函數是否工作。在端到端測試中,您將測試它是否正確顯示 – trichetriche

+0

請問您是否會發布e2e測試代碼? – Keshav