角度:一个组件的输出没有发出

角度:一个组件的输出没有发出

问题描述:

比方说,我有一个像下面这样的组件单元测试:角度:一个组件的输出没有发出

@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); 
    }); 
}); 

您可以使用这样的间谍:

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); 
    }); 
});