Angular 通过 spyOn 测试 stopPropagation

Angular testing stopPropagation via spyOn

我尝试测试我的 stopPropagation 行为。 当我在我的浏览器中测试它时它工作,控制台只打印 "button" 和 "between".

当我在测试中尝试使用 spyOn 时,它不起作用。 它说调用了该方法。

这是一个非常简单的例子。

Angular 分量:

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