[英]Angular: Unit test that a component's output is not emitted
假設我有一個如下所示的組件:
@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
,該組件將不輸出重復值。 是否有單元測試的最佳實踐從未調用可觀察訂閱? 雖然我所做的從技術上講是可行的,但感覺有點 hacky。
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);
});
});
你可以使用這樣的間諜:
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();
});
});
這就是你如何做到的。 一個變體是:
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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.