我使用 selenium-webdriver 编写了以下测试。 (还有一些用于 mocha 和 chai 的设置,但我还没有开始这项工作。)
我的问题是测试一直运行到我希望它等待页面加载并找到 ID 为“usergreeting”的元素,其中包含文本“欢迎,”+ 用户名。那时,测试抛出错误:
未捕获 NoSuchElementError:无法定位元素:{"method":"id","selector":"usergreeting"}
命令持续时间或超时:986 毫秒
但是,我可以看到(观看 Firefox 执行这些步骤)页面已加载并显示“#usergreeting”元素。
我不知道我做错了什么,但我显然做错了什么。可能,我还没有掌握 promise 的整个概念。 (请参阅我编写了 driver.wait()
语句的部分。)
感谢您的帮助。
var assert = require('assert'),
fs = require('fs'),
webdriver = require('selenium-webdriver');
require('mocha-as-promised')();
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.should();
describe('Login test', function() {
var driver, configObj, username, pwd;
this.timeout(6000);
before(function(done) {
driver = new webdriver
.Builder()
.usingServer('http://localhost:4444/wd/hub')
.withCapabilities(
{browserName: 'firefox'}
)
.build();
configObj = require('../test/config.json');
username = configObj.testuser;
pwd = configObj.testpass;
done();
});
it('User should be able to login', function(done) {
driver.get('http://127.0.0.1:5207/Login.php');
driver.findElement({id: 'UserNameEdit'}).sendKeys(username);
driver.findElement({id: 'PasswordEdit'}).sendKeys(pwd);
driver.findElement({id: 'LoginBtn'}).click();
driver.wait(function() {
return driver.findElement({id: 'usergreeting'}).innerText;
}, 3000)
.then(function(value) {
assert.equal(value, 'Welcome, ' + username);
done();
});
});
});
最佳答案
我认为问题出在你的 wait 语句中,它是一个轮询函数,它调用 findElement 将返回一个 NO_SUCH_ELEMENT 错误代码,在 webdriverjs 中这也是一个元素存在的断言。
您需要改为调用 driver.isElementPresent() 函数,一旦元素出现,您就可以调用 findElement 函数来获取它,因此请尝试以下方法:
var locator = By.id('usergreeting');
driver.wait(function () {
return driver.isElementPresent(locator);
}, 3000);
driver.findElement(locator).getText().then(function(txt) {
assert.equal(txt, 'Welcome, ' + username);
});
关于javascript - 这是 promise 错误吗? Selenium-webdriver 测试提交登录成功后找不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117103/