Scroll With Down Arrow in Puppeteer

Viewed 543

So I am working on a feature in my app that disables scroll by arrow key on the body when a menu is open, and leaves the behavior alone otherwise.

I am attempting to test that behavior in Puppeteer, but I can not seem to get the window to scroll when I press arrow down. Here's some examples of what I am doing both in implementation and in my tests:

        const disableArrowScroll = (event: KeyboardEvent) => {
            if (
                isOpen &&
                (event.key === 'ArrowDown' ||
                    event.key === 'ArrowUp' ||
                    event.key === 'ArrowLeft' ||
                    event.key === 'ArrowRight')
            ) {
                event.preventDefault();
            }
        };
it('does not effect scroll when menu is closed', async () => {
    await menuClosed(); // Times out if menu is not closed
    await page.focus('body');

    await keyboard.press('ArrowDown');

    expect(await page.evaluate(() => window.scrollY > 0)).toBeTruthy();
});

I've ensured that the page should be scrollable by limiting the viewport, and am really at a loss as to why window.scrollY remains 0. Am I missing something? In an actual running demo, the code seems to run as expected.

1 Answers

The issue is that, after initiating the arrow down keypress, you need to give the page time to scroll down. You can do that by changing...

await keyboard.press('ArrowDown');

...to...

await keyboard.press('ArrowDown');
await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1s
Related