How to scroll to element using Nightwatch?

前端 未结 5 2114
[愿得一人]
[愿得一人] 2021-02-19 02:27

I am using nightwatch for e2etesting my app. One of the tests fails because it cannot scroll to the element that it is testing I suspect. Question do I need to scroll or is ther

5条回答
  •  难免孤独
    2021-02-19 02:49

    Remember that:

    .execute() inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client.

    and

    Window.scrollTo() Scrolls to a particular set of coordinates in the document.

    Your test will look like this:

    module.exports = {
        'your-test': function (browser) {
            browser
                .url("http://example.com")
                .waitForElementPresent('body', 2000, "Be sure that the page is loaded")
                .execute('scrollTo(x, y)')
                .yourFirstAssertionHere()
                .yourSecondAssertionHere()
                ...
                .yourLastAssertionHere()
                .end()
        }
    };
    
    • If you know that the element with id myElement is at the top of the page you can just change x and y by 0 (just to be sure that you'll scroll to the top of the page).

    • If you need to get the exact values of x and y, you can use: getLocationInView() like this:

      module.exports = { 'your-test': function (browser) { browser .url("http://example.com") .waitForElementPresent('body', 2000, "Be sure that the page is loaded") .getLocationInView("#myElement", function(result) { //The x value will be: result.value.x //The y value will be: result.value.y }); } }

      .getLocationInView(): Determine an element's location on the screen once it has been scrolled into view... Returns The X and Y coordinates for the element on the page.

    Hope this help you.

提交回复
热议问题