我尝试测试我的stopPropagation
行为。当我在浏览器中对其进行测试时,该控制台将仅打印“按钮”和“之间”。
当我在测试中尝试spyOn时,它不起作用。它说该方法被调用了。
这里是一个非常简单的例子。
角组件:
@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>
测试:
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();
});
您的测试应该是:-
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();
});