元素 API
概述
新添加的 element()
全局对象为 Nightwatch 3 添加了 Selenium WebElement 类中的功能。
它支持在 Nightwatch 中定位元素的所有常用方法,以及使用 By()
构建的 Selenium 定位器,Selenium 定位器在 Nightwatch 中也可用,名为 by()
。
用法
使用常规 CSS(或 Xpath)选择器
const addButtonEl = element('button[type="submit"]');
使用 Nightwatch 选择器对象
const addButtonEl = element({
selector: 'button[type="button"]',
index: 0
});
Selenium 定位器
const locator = by.css('button[type="button"]');
const addButtonEl = element(locator);
Selenium WebElement 作为参数
// webElement is an instance of WebElement class from Selenium
const addButtonEl = element(webElement);
检索 Selenium WebElement 实例
const addButtonEl = element('button[type="submit"]');
const instance = await addButtonEl.findElement();
API 命令
常规 WebElement 实例中的所有现有方法都可用。如果调用方法,它将相应地添加到 Nightwatch 队列中。
可用的元素命令
- .clear()
- .click()
- .findElement()
- .findElements()
- .getAttribute()
- .getCssValue()
- .getDriver()
- .getId()
- .getRect()
- .getTagName()
- .getText()
- .isDisplayed()
- .isEnabled()
- .isSelected()
- .sendKeys()
- .submit()
- .takeScreenshot()
工作示例
下面的示例导航到 AngularJS 主页,并在那里添加一个新的待办事项到可用的待办事项示例应用中。
describe('angularjs homepage todo list', function() {
// using the new element() global utility in Nightwatch 2 to init elements
// before tests and use them later
const todoElement = element('[ng-model="todoList.todoText"]');
const addButtonEl = element('[value="add"]');
it('should add a todo using global element()', function() {
// adding a new task to the list
browser
.navigateTo('https://angularjs.org')
.sendKeys(todoElement, 'what is nightwatch?')
.click(addButtonEl);
// verifying if there are 3 tasks in the list
expect.elements('[ng-repeat="todo in todoList.todos"]').count.to.equal(3);
// verifying if the third task if the one we have just added
const lastElementTask = element({
selector: '[ng-repeat="todo in todoList.todos"]',
index: 2
});
expect(lastElementTask).text.to.equal('what is nightwatch?');
// find our task in the list and mark it as done
lastElementTask.findElement('input', function(inputResult) {
if (inputResult.error) {
throw inputResult.error;
}
const inputElement = element(inputResult.value);
browser.click(inputElement);
});
// verify if there are 2 tasks which are marked as done in the list
expect.elements('*[module=todoApp] li .done-true').count.to.equal(2);
});
});