简体   繁体   中英

Angular testing stopPropagation via spyOn

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM