2017-10-18 14 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); 
    } 
    } 
} 

私は以下のようなテストを書きました。私は、valueと同じ値でonValueChangeが呼び出された場合、重複した値を出力しないことをテストしたいと思います。観測可能なサブスクリプションが決して呼び出されないという単体テストのベストプラクティスはありますか?私は技術的にはうまくいったが、ちょっとハッキリしているようだ。

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); 
    }); 
}); 
関連する問題