Doublon
Doublon

Reputation: 117

How test a scroll from window event with Angular?

I'm trying to test this component:

export class HeaderComponent implements OnInit {

  sticky: boolean = false;

  @HostListener('window:scroll', ["$event"]) onScroll(event: Event) {
    let window = event.currentTarget as Window;
    console.log(window.scrollY);
    this.sticky = window.scrollY >= 30;
  }

  constructor() {
  }

  ngOnInit(): void {
  }
}

and there is the test :

  it("onScroll_Down_StickyIsTrue", () => {

  window.dispatchEvent(new Event("scroll"));
  window.scrollTo(0 , 50);

    expect(component.sticky).toBeTrue();
  });

And I don't know why the window.scrollY still 0.

Someone can help me ?

Upvotes: 0

Views: 3287

Answers (1)

Alan Grosz
Alan Grosz

Reputation: 1325

try with this:

it("onScroll_Down_StickyIsTrue", () => {
  component.onScroll({
    currentTarget: {
      scrollY: 31
    }
  } as any);
  expect(component.sticky).toBeTrue();
});

Upvotes: 1

Related Questions