Let's say I have a component like the following:
@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);
}
}
}
I've written a test like the one below. I want to test that if onValueChange
is called with the same value as value
, the component will not output the duplicate value. Is there a best practice for unit testing that an observable subscription is never called? While what I did technically works, it feels a little 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);
});
});
You can use a spy like this:
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();
});
});
That's pretty much how you do it. A variation is:
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With