【问题标题】:using setInterval for keep scrolling in nightwatch js使用 setInterval 在 nightwatch js 中保持滚动
【发布时间】:2017-11-13 01:57:50
【问题描述】:

我有一个 nightwatch js 脚本,它将在我的网页中滚动运行 这是我的自定义命令脚本

'use strict'

exports.command = function (param) {
    this.execute(function (param) {
        $(window).scrollTop(param)
    }, [param])
}

然后从我的测试文件中调用该滚动脚本。这是我的脚本

module.exports = {
    'Scrolling testing': function (client) {
        client.url('http://localhost:1200/').waitForElementVisible('div.user-item', 5000);
        let i = 50
        setInterval(function () {
            console.log(i)
            client.scrollTo(i)
            i += 50
        }, 500)
    }
};

我只想使用 setInterval 每 500 毫秒进行一次滚动操作,但浏览器只滚动一次(但控制台日志继续运行)。任何人都可以解决这个问题..

抱歉英语不好:(

【问题讨论】:

    标签: javascript google-chrome selenium-webdriver nightwatch.js


    【解决方案1】:

    我会做一些选择来获得你想要的行为,但我不知道哪一个会让你满意:

    1. 使用perform (See documentation here)

    perform 命令使您能够执行一些代码,它可以是异步的,因此您可以执行示例#1 之类的操作(出于某种原因,如果我将代码放在下面,它不会被格式化)

    1. 使用executeAsync (See documentation here) 代替execute

    execute 命令同步运行,所以可能在第一次执行后它会继续测试然后完成。因此,改为使用executeAsync 并将整个 setInterval 函数移到其中,这样您就不需要自定义命令(恕我直言,我将删除它,因为没有做太多事情)。见例子#2

    示例#1

    client
        .url('http://localhost:1200/')
        .waitForElementVisible('div.user-item', 5000)
        .perform(function(client, done){
            let i = 50, maxExecutions = 10, intervalTime = 0;
            intervalTime = setInterval(function () {
                console.log(i);
                client.scrollTo(i);
                i += 50;
                maxExecutions++;
                if(maxExecutions===10) {
                    clearInterval(intervalTime); //to prevent an infinite loop
                    done();
                }
            }, 500)
        })
    

    示例#2

    module.exports = {
        'Scrolling testing': function (client) {
            client
                .url('http://localhost:1200/')
                .waitForElementVisible('div.user-item', 5000)
                .executeAsync(function (param, done) {
                    let i = 50, maxExecutions = 10, intervalTime = 0;
                    intervalTime = setInterval(function () {
                        maxExecutions++;
                        console.log(i);//will be logged on browser console
                        $(window).scrollTop(param);
                        i += 50
                        if(maxExecutions===10){
                            clearInterval(intervalTime);
                            done(/*you can send some data here*/)
                        }
                    }, 500)
                }, [], function(/*the data that you have send*/){
                    //do something
                })
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多