Nightwatch.js 从输入中获取值并在下一步中使用它

Oro*_*vid 4 javascript automated-tests selenium-webdriver nightwatch.js

我正在尝试运行 Nightwatch 脚本,该脚本将打开一个 url,然后它将从输入中获取值,并在下一页中使用该值。

请看下面的代码:

var conf = require('../../nightwatch.conf.BASIC.js');

module.exports = {
    'nightwatch flow': function (browser) {
        var first_name;
        browser
            .url('http://example:3000')
            .getValue('input[name="first_name"]', function(result){
                first_name = result.value;
            })
            .setValue('input[name="amount"]', 101)
            .click('input[name=continue]')
            .clearValue('input[name="first_name"]')
            .setValue('input[name="first_name"]', first_name)
            .click('button[name=next]')
            .end();
    }
};
Run Code Online (Sandbox Code Playgroud)

得到setValue('input[name="first_name"]', first_name) “未定义”

first_name 参数正在回调函数内更新。我需要 setValue 函数使用更新后的值。提前致谢

Oro*_*vid 5

我找到了一个解决方法:

var conf = require('../../nightwatch.conf.BASIC.js');

var first_name;

module.exports = {
    'nightwatch flow': function (browser) {
        browser
            .url('http://example:3000')
            .getValue('input[name="first_name"]', function(result){
                first_name = result.value;
            })
            .setValue('input[name="amount"]', 101)
            .click('input[name=continue]')
            .clearValue('input[name="first_name"]')
            .setValue('input[name="first_name"]', "", function(){
                browser.setValue('input[name="first_name"]', first_name)
            })
            .click('button[name=next]')
            .end();
    }
};
Run Code Online (Sandbox Code Playgroud)

解决方案是在回调中再次使用 browser.setValue 。

  • 您在这里遇到的问题是由于 Nightwatch 的命令队列造成的。如果您只是将单个 setValue 函数包装在 browser.perform() 中,它将执行您想要的操作。问题是您的原始 setValue 在 getValue 回调运行之前就传递了first_name。请参阅 https://github.com/nightwatchjs/nightwatch/wiki/Understanding-the-Command-Queue (2认同)