2017-10-18 37 views
1

比方說,我有一個像下面這樣的組件單元測試:角度:一個組件的輸出沒有發出

@Component({ 
    selector: 'example', 
    template: ` ` 
}) 
export class ExampleComponent { 
    value: any; 
    @Output() output: EventEmitter<any> = new EventEmitter(); 

    onValueChange(newValue: any) { 
    if (newValue !== this.value) { 
     this.value = newValue; 
     this.output.emit(newValue); 
    } 
    } 
} 

我寫類似下面的測試。我想測試一下,如果調用onValueChange的值與value的值相同,組件將不會輸出重複值。是否有單元測試的最佳做法,即從未調用可觀察的訂閱?雖然我在技術上做了什麼,但感覺有點冒險。

describe('ExampleComponent',() => { 
    it('should not output duplicate values',() => { 
    const component = new ExampleComponent(); 
    component.value = 1; 
    component.output.subscribe(value => { 
     // if the output is not triggered then we'll never reach this 
     // point and the test will pass 
     expect(true).toEqual(false); 
    }); 
    component.onValueChange(1); 
    }); 
}); 

回答

2

您可以使用這樣的間諜:

describe('ExampleComponent',() => { 
    it('should not output duplicate values',() => { 
    const component = new ExampleComponent();   
    spyOn(component.output, 'emit'); 

    component.value = 1; 
    component.onValueChange(1); 

    expect(component.output.emit).not.toHaveBeenCalled(); 
    }); 
}); 
0

這幾乎是你如何做到的。一個變化是:

describe('ExampleComponent',() => { 
    it('should not output duplicate values',() => { 
    const component = new ExampleComponent(); 
    let numEvents = 0; 
    component.value = 1; 
    component.output.subscribe(value => ++numEvents); 
    component.onValueChange(1); 
    expect(numEvents).toEqual(0); 
    }); 
});