Repository: nightwatchjs/nightwatch
Pull request #2711 (2021-05-21 13:56:21)

Features/ isSelected element command
Thanks in advance for your contribution. Please follow the below steps in submitting a pull request, as it will help us with reviewing it quicker.

- [ ] Create a new branch from master (e.g. `features/my-new-feature` or `issue/123-my-bugfix`);
- [ ] If you're fixing a bug also create an issue if one doesn't exist yet;
- [ ] If it's a new feature explain why do you think it's necessary. Please check with the maintainers beforehand to make sure it is something that we will accept. Usually we only accept new features if we feel that they will benefit the entire community;
- [ ] Please avoid sending PRs which contain drastic or low level changes. If you are certain that the changes are needed, please discuss them beforehand and indicate what the impact will be;
- [ ] If your change is based on existing functionality please consider refactoring first. Pull requests that duplicate code will most likely be ignored;
- [ ] Do not include changes that are not related to the issue at hand;
- [ ] Follow the same coding style with regards to spaces, semicolons, variable naming etc.;
- [ ] Always add unit tests - PRs without tests are most of the times ignored.



Patch:
diff --git a/lib/api/assertions/selected.js b/lib/api/assertions/selected.js
new file mode 100644
index 00000000..d8d6f108
--- /dev/null
+++ b/lib/api/assertions/selected.js
@@ -0,0 +1,48 @@
+
+/**
+ * Checks if the given element is selected.
+ *
+ * ```
+ * this.demoTest = function (browser) {
+ *   browser.assert.selected('.should_be_selected');
+ *   browser.assert.selected({selector: '.should_be_selected'});
+ *   browser.assert.selected({selector: '.should_be_selected', suppressNotFoundErrors: true});
+ * };
+ * ```
+ *
+ * @method selected
+ * @param {string|object} definition The selector (CSS / Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide/working-with-page-objects/#element-properties).
+ * @param {string} [msg] Optional log message to display in the output. If missing, one is displayed by default.
+ * @api assertions
+ */
+exports.assertion = function(definition, msg) {
+  this.options = {
+    elementSelector: true
+  };
+
+  this.formatMessage = function() {
+    const message = msg || `Testing if element %s ${this.negate ? 'is not selected' : 'is selected'}`;
+    
+    return {
+      message,
+      args: [this.elementSelector]
+    };
+  };
+
+  this.expected = function() {
+    return this.negate ? 'is not selected' : 'is selected';
+  };
+
+  this.evaluate = function(value) {
+    return value === true;
+  };
+
+  this.actual = function(passed) {
+    return passed ? 'selected' : 'not selected';
+  };
+
+  this.command = function(callback) {
+    this.api.isSelected(definition, callback);
+  };
+  
+};
diff --git a/lib/api/element-commands/isSelected.js b/lib/api/element-commands/isSelected.js
new file mode 100644
index 00000000..23514aac
--- /dev/null
+++ b/lib/api/element-commands/isSelected.js
@@ -0,0 +1,57 @@
+const BaseElementCommand = require('./_baseElementCommand.js');
+
+/**
+ * Determines if an element is selected.
+ *
+ * @example
+ * module.exports = {
+ *   demoTest(browser) {
+ *     browser.isSelected('#main select option.first', function(result) {
+ *       this.assert.equal(typeof result, "object");
+ *       this.assert.equal(result.status, 0);
+ *       this.assert.equal(result.value, true);
+ *     });
+ *
+ *     // with explicit locate strategy
+ *     browser.isSelected('css selector', '#main select option.first');
+ *
+ *     // with selector object - see https://nightwatchjs.org/guide#element-properties
+ *     browser.isSelected({
+ *       selector: '#main ul li a',
+ *       index: 1,
+ *       suppressNotFoundErrors: true
+ *     });
+ *
+ *     browser.isSelected({
+ *       selector: '#main select option.first',
+ *       timeout: 2000 // overwrite the default timeout (in ms) to check if the element is present
+ *     });
+ *   },
+ *
+ *   demoTestAsync: async function(browser) {
+ *     const result = await browser.isSelected('#main select option.first');
+ *     console.log('isVisible result', result);
+ *   }
+ * }
+ *
+ * @method isSelected
+ * @syntax .isSelected(selector, callback)
+ * @syntax .isSelected(using, selector, callback)
+ * @param {string} [using] The locator strategy to use. See [W3C Webdriver - locator strategies](https://www.w3.org/TR/webdriver/#locator-strategies)
+ * @param {string|object} selector The selector (CSS/Xpath) used to locate the element. Can either be a string or an object which specifies [element properties](https://nightwatchjs.org/guide#element-properties).
+ * @param {function} callback Callback function which is called with the result value.
+ * @link /#is-element-selected
+ * @api protocol.elementstate
+ */
+class IsSelected extends BaseElementCommand {
+  get extraArgsCount() {
+    return 0;
+  }
+
+  get elementProtocolAction() {
+    return 'isElementSelected';
+  }
+
+}
+
+module.exports = IsSelected;
\ No newline at end of file


Test patch:
diff --git a/test/src/api/assertions/testSelected.js b/test/src/api/assertions/testSelected.js
new file mode 100644
index 00000000..91e8cd0f
--- /dev/null
+++ b/test/src/api/assertions/testSelected.js
@@ -0,0 +1,172 @@
+const assert = require('assert');
+const Globals = require('../../../lib/globals.js');
+
+describe('assert.selected', function () {
+  const assertionName = 'selected';
+  const api = 'isSelected';
+
+  function assertionTest(opts) {
+    return Globals.assertion(assertionName, api, opts);
+  }
+
+  it('selected assertion passed', function () {
+    return assertionTest({
+      args: ['.test_element', 'Test message'],
+      commandResult: {
+        status: 0,
+        value: true
+      },
+      assertArgs: true,
+      assertMessage: true,
+      assertion({reporter, instance, failure, err}) {
+        assert.strictEqual(err, undefined);
+        assert.deepStrictEqual(instance.options, {elementSelector: true});
+        assert.strictEqual(failure, false);
+        assert.strictEqual(instance.hasFailure(), false);
+      }
+    });
+  });
+
+  it('.not.selected assertion passed', function () {
+    return assertionTest({
+      args: ['.test_element'],
+      commandResult: {
+        status: 0,
+        value: false
+      },
+      negate: true,
+
+      assertion({reporter, instance, queueOpts, err, message}) {
+        assert.strictEqual(typeof err, 'undefined');
+        assert.strictEqual(queueOpts.negate, true);
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.strictEqual(instance.getValue(), false);
+        assert.strictEqual(instance.getActual(), 'not selected');
+        assert.strictEqual(
+          instance.message,
+          'Testing if element <.test_element> is not selected'
+        );
+        assert.ok(
+          message.startsWith(
+            'Testing if element <.test_element> is not selected'
+          ),
+          message
+        );
+      }
+    });
+  });
+
+  it('.not.selected assertion failed', function () {
+    return assertionTest({
+      args: ['.test_element'],
+      commandResult: {
+        status: 0,
+        value: true
+      },
+      negate: true,
+      assertError: true,
+
+      assertion({reporter, instance, queueOpts, err}) {
+        assert.strictEqual(queueOpts.negate, true);
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.strictEqual(instance.getValue(), true);
+        assert.strictEqual(instance.getActual(), 'selected');
+        assert.strictEqual(
+          err.message,
+          `Error while running "selected" command: Testing if element <.test_element> is not selected in 5ms - expected "is not selected" but got: "selected" (${instance.elapsedTime}ms)`
+        );
+      }
+    });
+  });
+
+  it('selected assertion passed with selector object', function () {
+    return assertionTest({
+      args: [{selector: '.test_element'}],
+      commandResult: {
+        status: 0,
+        value: true
+      },
+      assertion({instance, failure, message, err}) {
+        assert.strictEqual(err, undefined);
+        assert.deepStrictEqual(instance.options, {elementSelector: true});
+        assert.strictEqual(instance.getActual(), 'selected');
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.ok(
+          message.startsWith('Testing if element <.test_element> is selected'),
+          message
+        );
+        assert.strictEqual(failure, false);
+      }
+    });
+  });
+
+  it('selected assertion passed with selector object and timeout', function () {
+    return assertionTest({
+      args: [{selector: '.test_element', timeout: 10, retryInterval: 15}],
+      commandResult: {
+        status: 0,
+        value: true
+      },
+      assertion({instance, failure, message, err}) {
+        assert.strictEqual(err, undefined);
+        assert.deepStrictEqual(instance.options, {elementSelector: true});
+        assert.strictEqual(instance.getActual(), 'selected');
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.strictEqual(instance.retryAssertionTimeout, 10);
+        assert.strictEqual(instance.rescheduleInterval, 15);
+        assert.ok(
+          message.startsWith('Testing if element <.test_element> is selected'),
+          message
+        );
+        assert.strictEqual(failure, false);
+      }
+    });
+  });
+
+  it('selected assertion failed', function () {
+    return assertionTest({
+      args: ['.test_element'],
+      commandResult: {
+        status: 0,
+        value: false
+      },
+      assertError: true,
+      assertResult: true,
+      assertion({instance, failure}) {
+        assert.strictEqual(instance.getActual(), 'not selected');
+        assert.strictEqual(
+          failure,
+          'Expected "is selected" but got: "not selected"'
+        );
+      }
+    });
+  });
+
+  it('selected assertion not - element not found', function () {
+    return assertionTest({
+      args: ['.test_element'],
+      commandResult: {
+        status: -1
+      },
+      assertError: true,
+      assertFailure: true,
+      assertResult: true,
+      assertion({instance, failure, err}) {
+        assert.strictEqual(
+          instance.getActual(),
+          'element could not be located'
+        );
+        assert.strictEqual(instance.expected(), 'is selected');
+        assert.strictEqual(instance.getValue(), null);
+        assert.strictEqual(
+          failure,
+          'Expected "is selected" but got: "element could not be located"'
+        );
+        assert.strictEqual(
+          err.message,
+          `Error while running "selected" command: Testing if element <.test_element> is selected in 5ms - expected "is selected" but got: "element could not be located" (${instance.elapsedTime}ms)`
+        );
+      }
+    });
+  });
+});
diff --git a/test/src/api/commands/testIsSelected.js b/test/src/api/commands/testIsSelected.js
new file mode 100644
index 00000000..e23c6d8d
--- /dev/null
+++ b/test/src/api/commands/testIsSelected.js
@@ -0,0 +1,40 @@
+const assert = require('assert');
+const MockServer  = require('../../../lib/mockserver.js');
+const CommandGlobals = require('../../../lib/globals/commands.js');
+
+describe('isSelected', function() {
+  before(function(done) {
+    CommandGlobals.beforeEach.call(this, done);
+  });
+
+  afterEach(function() {
+    MockServer.removeMock({
+      url: '/wd/hub/session/1352110219202/element/0/selected',
+      method: 'GET'
+    });
+  });
+
+  after(function(done) {
+    CommandGlobals.afterEach.call(this, done);
+  });
+
+  it('client.isEnabled()', function(done) {
+    MockServer.addMock({
+      url: '/wd/hub/session/1352110219202/element/0/selected',
+      method: 'GET',
+      response: JSON.stringify({
+        sessionId: '1352110219202',
+        status: 0,
+        value: true
+      })
+    });
+
+    this.client.api.isSelected('css selector', '#weblogin', function callback(result) {
+      assert.strictEqual(result.value, true);
+    }).isSelected('#weblogin', function callback(result) {
+      assert.strictEqual(result.value, true);
+    });
+
+    this.client.start(done);
+  });
+});