scrollToElement(selector [,options])

🚧

This is a TDK feature

This is not supported in Testim's visual editor

Scroll to a given element on the screen.

  • selector {string | TDKStepLocator} a CSS selector or smart locator for the element
  • options {object}
    • scrollTarget {string} CSS selector for the element we scroll on, by default body
  • returns: Promise that fulfills when the action is complete.
// ✅ scroll to an element with class 'book' 
await scrollToElement('.book');
// ✅ scroll to the picture element inside a container with class gallery  
await scrollToElement('picture', {
  scrollTarget: '.gallery'
});
// ✅ scroll to the email input in the scrollable login form with locators
await scrollToElement(l('email'), {
  scrollTarget: l('login-form')
});
// ❌ need to pass a selector
await scrollToElement();
// ❌ the scroll target needs to be a scrollable element selector/locator
await scrollToElement('input', {
  scrollTarget: 15
});
await scrollToElement('input', {
  scrollTarget: 'head'
});

Full example

'use strict';

const { expect } = require('chai');
const {g, test, scrollToElement, evaluate, describe} = require('testim');

describe("scrollToElement", () => {
    test("scroll to element inside element", async () => {
        await go('http://jsbin.testim.io/caf/3');
        const scrolledBefore = await evaluate(() => document.querySelector("#scrollable-to").parentElement.scrollTop);
        expect(scrolledBefore).to.equal(0);
        await scrollToElement('#scrollable-to', { scrollTarget: 'body > div' });
        const scrolled = await evaluate(() => document.querySelector("#scrollable-to").parentElement.scrollTop);
        expect(scrolled).to.be.above(1);
    });

    test("scroll to element - body", async () => {
        await go('http://jsbin.testim.io/kot/2');
        await scrollToElement('body > div > div:nth-child(2)');
        const scrolled = await evaluate(() => document.documentElement.scrollTop);
        expect(scrolled).to.be.above(10);
    });
});