要素API

概要

新たに追加された element() グローバルオブジェクトは、Nightwatch 3 に Selenium WebElement クラスにある機能を追加します。

Nightwatch の通常の要素の探し方、そして `By()` を使って作られた Selenium ロケーターもサポートしています。`by()` というグローバル名で Nightwatch でも利用可能です。

使用方法

通常の 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 アプリに新しい 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); }); });