I try to test my stopPropagation
behavior.
When i test it in my browser it works, the console prints only "button" and "between".
When i try the spyOn in the test, it doesnt work. It says that the method was called.
Here is a very simple example.
Angular Component:
@Component({
selector: 'app-prevent-event',
templateUrl: './prevent-event.component.html',
styleUrls: ['./prevent-event.component.scss']
})
export class PreventEventComponent implements OnInit {
constructor() { }
ngOnInit() {
}
clickDiv() {
console.log("div");
}
clickButton() {
console.log("button");
}
clickDivBetween(event) {
event.stopPropagation();
console.log("between");
}
}
HMTL:
<div (click)="clickDiv()">
<div (click)="clickDivBetween($event)">
<button id="btn1" (click)="clickButton()">Test</button>
</div>
</div>
Test:
it('should prevent the div click', () => {
const spy1 = spyOn(component, "clickButton");
const spy2 = spyOn(component, "clickDivBetween");
const spy3 = spyOn(component, "clickDiv");
fixture.debugElement.query(By.css("#btn1")).nativeElement.click();
expect(spy1).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
expect(spy3).not.toHaveBeenCalled();
});
Your test should be :-
it('should prevent the div click', () => {
const spy1 = spyOn(component, "clickButton");
const spy3 = spyOn(component, "clickDiv");
fixture.debugElement.query(By.css("#btn1")).nativeElement.click();
expect(spy3).not.toHaveBeenCalled();
});