【问题标题】:Angular testing stopPropagation via spyOn通过 spyOn 进行角度测试 stopPropagation
【发布时间】:2020-06-07 12:37:53
【问题描述】:

我尝试测试我的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();
  });

【问题讨论】:

    标签: javascript angular testing karma-jasmine event-propagation


    【解决方案1】:

    你的测试应该是:-

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

    【讨论】:

    • 谢谢...我发现(模拟)了我的 stopPropagation 方法调用 facepalm 喝咖啡的时间:D ...无论如何谢谢...对于我现在使用的真实案例.and.callThrough() 因为我想要第二个间谍并且现在可以工作了:)
    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2019-05-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多