元素 API

概述

新加入的 element() 全域物件將 Selenium WebElement 類別的功能新增到 Nightwatch 3 中。

它支援 Nightwatch 中所有常用的元素定位方式,以及使用 By() 建構的 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 佇列中。

可用的元素命令

運作範例

下面的範例會導覽至 AngularJS 首頁,並在可用的範例 ToDo 應用程式中新增一個新的待辦事項。

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); }); });