Repository: nightwatchjs/nightwatch
Pull request #4123 (2024-03-13 08:37:43)

Fix `waitUntil` not working with async/await.
WaitUntil was getting prematurely resolved when used with async await. That is because inside the command queue tree, whenever child nodes are resolved, the parent node is also automatically called to be resolved which was causing pre mature resolution of waitUntil.

CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/nightwatchjs/nightwatch?pullRequest=4123) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/nightwatchjs/nightwatch?pullRequest=4123) before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/nightwatchjs/nightwatch?pullRequest=4123) it.</sub>

Patch:
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 2b477275..e54f0e97 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,5 +1,6 @@
 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.
 
+- [ ] Before marking your PR for review, please test and verify your changes by making appropriate modifications to any of the Nightwatch example tests (present in `examples/tests` directory of the project) and running them. `ecosia.js` and `duckDuckGo.js` are good examples to work with.
 - [ ] 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;
diff --git a/examples/pages/google/search.js b/examples/pages/google/search.js
index 430d8dc1..17ff4013 100644
--- a/examples/pages/google/search.js
+++ b/examples/pages/google/search.js
@@ -30,7 +30,7 @@ module.exports = {
     consentModal,
 
     searchBar: {
-      selector: 'input[name=q]'
+      selector: 'textarea[name=q]'
     },
 
     submitButton: {
diff --git a/examples/pages/google/searchResults.js b/examples/pages/google/searchResults.js
index 35061c08..458e9e61 100644
--- a/examples/pages/google/searchResults.js
+++ b/examples/pages/google/searchResults.js
@@ -1,5 +1,8 @@
 const util = require('util');
-const menuXpath = '//div[contains(@class, "hdtb-mitem")][contains(., "%s")]';
+
+// starting xpath with './/' tells browser to begin search from the current element,
+// while starting with '//' tells browser to begin search from the start of html document.
+const menuXpath = './/span[contains(text(), "%s")]';
 
 const menuCommands = {
   productIsSelected: function (product, callback) {
@@ -18,15 +21,15 @@ module.exports = {
   },
   sections: {
     menu: {
-      selector: '#hdtb-msb',
+      selector: 'div[role="navigation"] div[data-st-cnt="mode"]',
       commands: [menuCommands],
       elements: {
-        all: {
-          selector: util.format(menuXpath, 'All'),
+        maps: {
+          selector: util.format(menuXpath, 'Maps'),
           locateStrategy: 'xpath',
           index: 0
         },
-        video: {
+        videos: {
           selector: util.format(menuXpath, 'Videos'),
           locateStrategy: 'xpath',
           index: 0
diff --git a/lib/api/_loaders/_command-loader.js b/lib/api/_loaders/_command-loader.js
index ea738cb0..6843fc73 100644
--- a/lib/api/_loaders/_command-loader.js
+++ b/lib/api/_loaders/_command-loader.js
@@ -34,8 +34,9 @@ class BaseCommandLoader extends BaseLoader {
     const redact = this.module.RedactParams || false;
     const alwaysAsync = this.module.alwaysAsync || false;
     const isTraceable = this.module.isTraceable;
+    const avoidPrematureParentNodeResolution = !!this.module.avoidPrematureParentNodeResolution;
 
-    return {redact, alwaysAsync, isTraceable};
+    return {redact, alwaysAsync, isTraceable, avoidPrematureParentNodeResolution};
   }
 
   validateMethod(parent) {
@@ -75,7 +76,7 @@ class BaseCommandLoader extends BaseLoader {
   }
 
   getTargetNamespace(parent) {
-    let namespace = this.namespace;
+    const namespace = this.namespace;
 
     if (!parent) {
       return namespace;
diff --git a/lib/api/protocol/waitUntil.js b/lib/api/protocol/waitUntil.js
index 97f84bd9..feb693a3 100644
--- a/lib/api/protocol/waitUntil.js
+++ b/lib/api/protocol/waitUntil.js
@@ -61,6 +61,10 @@ module.exports = class WaitUntil extends ProtocolAction {
     return true;
   }
 
+  static get avoidPrematureParentNodeResolution() {
+    return true;
+  }
+
   //timeMs, retryInterval, message, callback = function(r) {return r}
   async command(conditionFn, ...args) {
     let callback = function(r) {return r};
diff --git a/lib/api/web-element/commands/getRect.js b/lib/api/web-element/commands/getRect.js
index 9ecdaaf5..7d3923ec 100644
--- a/lib/api/web-element/commands/getRect.js
+++ b/lib/api/web-element/commands/getRect.js
@@ -29,6 +29,8 @@
  * @syntax browser.element(selector).getRect()
  * @see https://www.w3.org/TR/webdriver#dfn-get-element-rect
  * @returns {ScopedValue<{ width: number, height: number }>}
+ * @alias getSize
+ * @alias getLocation
  */
 module.exports.command = function() {
   return this.runQueuedCommandScoped('getElementRect');
diff --git a/lib/api/web-element/commands/takeScreenshot.js b/lib/api/web-element/commands/takeScreenshot.js
index 9f4ab1b2..0818ebd0 100644
--- a/lib/api/web-element/commands/takeScreenshot.js
+++ b/lib/api/web-element/commands/takeScreenshot.js
@@ -6,13 +6,13 @@
  *   demoTest(browser: NightwatchAPI): void {
  *     const screenshot = browser.element('#main').takeScreenshot();
  *     screenshot.then((screenshotData) => {
- *       require('fs').writeFile('out.png', screenshotData, 'base64');
+ *       require('fs/promises').writeFile('out.png', screenshotData, 'base64');
  *     });
  *   },
  *
  *   async demoTestAsync(browser: NightwatchAPI): Promise<void> {
  *     const screenshotData = await browser.element('#main').takeScreenshot();
- *     require('fs').writeFile('out.png', screenshotData, 'base64');
+ *     require('fs/promises').writeFile('out.png', screenshotData, 'base64');
  *   }
  * }
  *
diff --git a/lib/api/web-element/scoped-element.js b/lib/api/web-element/scoped-element.js
index 69cd4212..1aaee5f8 100644
--- a/lib/api/web-element/scoped-element.js
+++ b/lib/api/web-element/scoped-element.js
@@ -22,9 +22,10 @@ class ScopedWebElement {
       'findAllByRole': ['getAllByRole'],
       'findAllByPlaceholderText': ['getAllByPlaceholderText'],
       'findAllByAltText': ['getAllByAltText'],
-      'getRect': ['getSize', 'getLocation'],
+      'getRect': ['getSize', 'getLocation', 'rect'],
       'getProperty': ['property'],
-      'getCssProperty': ['css']
+      'getCssProperty': ['css'],
+      'isVisible': ['isDisplayed']
     };
   }
 
diff --git a/lib/core/asynctree.js b/lib/core/asynctree.js
index 72152e56..0493834a 100644
--- a/lib/core/asynctree.js
+++ b/lib/core/asynctree.js
@@ -91,6 +91,18 @@ class AsyncTree extends EventEmitter{
     return parentNode.childNodes.filter(item => item !== node && !item.done).length > 0;
   }
 
+  shouldAvoidParentNodeResolution(node) {
+    const parentNode = node.parent;
+
+    if (!parentNode || parentNode.isRootNode) {
+      return true;
+    }
+
+    const result = parentNode.options?.avoidPrematureParentNodeResolution;
+
+    return Boolean(result);
+  }
+
   shouldRejectNodePromise(err, node = this.currentNode) {
     if ((err.isExpect || node.namespace === 'assert') && this.currentNode.isES6Async) {
       return true;
@@ -183,13 +195,14 @@ class AsyncTree extends EventEmitter{
 
     setTimeout(() => {
       const stillInProgress = this.otherChildNodesInProgress(node);
+      const avoidPrematureParentNodeResolution = this.shouldAvoidParentNodeResolution(node);
 
       if (node.context && node.context instanceof EventEmitter) {
         node.context.emit('complete');
       }
 
       const isAssertion = node.parent && (node.parent.namespace === 'assert' || node.parent.namespace === 'verify');
-      if (node.parent && !node.parent.isRootNode && !isAssertion && !stillInProgress) {
+      if (node.parent && !node.parent.isRootNode && !isAssertion && !stillInProgress && !avoidPrematureParentNodeResolution) {
         node.done = true;
         this.resolveNode(node.parent, result, ++times);
       }
diff --git a/lib/runner/cli/cli.js b/lib/runner/cli/cli.js
index 5d14ef2c..5b4e7d5d 100644
--- a/lib/runner/cli/cli.js
+++ b/lib/runner/cli/cli.js
@@ -293,7 +293,7 @@ class CliRunner {
 
       if (plugins.length > 0) {
         plugins.forEach((plugin) => {
-          if (plugin.globals && Utils.isFunction(plugin.globals.registerEventHandlers)){
+          if (plugin.globals && Utils.isFunction(plugin.globals.registerEventHandlers)) {
             plugin.globals.registerEventHandlers(NightwatchEventHub);
           }
         });
@@ -450,7 +450,11 @@ class CliRunner {
   }
 
   isTestWorkersEnabled() {
-    const testWorkers =  this.test_settings.testWorkersEnabled && !singleSourceFile(this.argv);
+    if (this.testRunner.supportsParallelTestSuiteRun === false) {
+      return false;
+    }
+
+    const testWorkers = this.test_settings.testWorkersEnabled && !singleSourceFile(this.argv);
     if (!testWorkers) {
 
       if (this.argv.debug) {
@@ -466,7 +470,7 @@ class CliRunner {
 
       if (isMobile(desiredCapabilities) && !this.usingServer(this.testEnvSettings[env])) {
 
-        if  (Concurrency.isWorker()) {
+        if (Concurrency.isWorker()) {
           Logger.info('Disabling parallelism while running tests on mobile platform');
         }
 
diff --git a/package-lock.json b/package-lock.json
index cab803a9..da13123a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
 {
   "name": "nightwatch",
-  "version": "3.4.1",
+  "version": "3.5.0",
   "lockfileVersion": 2,
   "requires": true,
   "packages": {
     "": {
       "name": "nightwatch",
-      "version": "3.4.1",
+      "version": "3.5.0",
       "license": "MIT",
       "dependencies": {
         "@nightwatch/chai": "5.0.3",
diff --git a/package.json b/package.json
index 44b8556f..db55b8c8 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
 {
   "name": "nightwatch",
   "description": "Easy to use Node.js based end-to-end testing solution for web applications using the W3C WebDriver API.",
-  "version": "3.4.1",
+  "version": "3.5.0",
   "author": "Andrei Rusu",
   "homepage": "https://nightwatchjs.org",
   "main": "./lib/index.js",
diff --git a/types/web-element.d.ts b/types/web-element.d.ts
index dc2f87aa..d8fc0c71 100644
--- a/types/web-element.d.ts
+++ b/types/web-element.d.ts
@@ -139,6 +139,12 @@ export interface ScopedElement extends Element, PromiseLike<WebElement> {
 
   getRect(): ElementValue<ScopedElementRect>;
 
+  rect(): ElementValue<ScopedElementRect>;
+
+  getSize(): ElementValue<ScopedElementRect>;
+
+  getLocation(): ElementValue<ScopedElementRect>;
+
   getTagName(): ElementValue<string>;
 
   getText(): ElementValue<string>;
@@ -175,8 +181,6 @@ export interface ScopedElement extends Element, PromiseLike<WebElement> {
 
   getCssProperty(name: string): ElementValue<string>;
 
-  getSize(): ElementValue<ScopedElementRect>;
-
   getValue(): ElementValue<string | null>;
 
   setValue<E extends readonly unknown[]>(...keys: E): Promise<WebElement>;
@@ -194,6 +198,7 @@ export interface ScopedElement extends Element, PromiseLike<WebElement> {
   isEnabled(): ElementValue<boolean>;
 
   isVisible(): ElementValue<boolean>;
+  isDisplayed(): ElementValue<boolean>;
 }
 
 type WaitUntilOptions = {


Test patch:
diff --git a/examples/tests/googlePageObject.js b/examples/tests/googlePageObject.js
index 49be3b26..1823599a 100644
--- a/examples/tests/googlePageObject.js
+++ b/examples/tests/googlePageObject.js
@@ -1,30 +1,10 @@
 describe('google search with consent form - page objects', function() {
-
-  this.disabled = this.argv.env !== 'chrome';
-
   const homePage = browser.page.google.search();
-  const consentPage = browser.page.google.consent();
 
   before(async () => homePage.navigate());
 
   after(async (browser) => browser.quit());
 
-  it.only('should complete the consent form', async function (browser) {
-
-    // const consentForm = consentPage.section.consentForm;
-    // const submitButton = consentForm.element('@submitButton');
-
-    const oldElement = await browser.element('css selector', 'body');
-    const consentPresent = await homePage.isPresent('@consentModal');
-
-    if (consentPresent) {
-      await homePage.expect.section('@consentModal').to.be.visible;
-
-      const {consentModal} = homePage.section;
-      await consentModal.click('@rejectAllButton');
-    }
-  });
-
   it('should find nightwatch.js in results', function (browser) {
     homePage.setValue('@searchBar', 'Nightwatch.js');
     homePage.submit();
@@ -37,6 +17,6 @@ describe('google search with consent form - page objects', function() {
     resultsPage.expect.section('@menu').to.be.visible;
 
     const menuSection = resultsPage.section.menu;
-    menuSection.expect.element('@all').to.be.visible;
+    menuSection.expect.element('@videos').to.be.visible;
   });
 });
diff --git a/lib/runner/test-runners/cucumber.js b/lib/runner/test-runners/cucumber.js
index 6a505a03..bb270a63 100644
--- a/lib/runner/test-runners/cucumber.js
+++ b/lib/runner/test-runners/cucumber.js
@@ -246,6 +246,10 @@ class CucumberSuite extends TestSuite {
 
 class CucumberRunnner extends Runner {
   get supportsConcurrency() {
+    return true;
+  }
+
+  get supportsParallelTestSuiteRun() {
     return false;
   }
 
diff --git a/test/cucumber-integration-tests/testCucumberTestsInParallel.js b/test/cucumber-integration-tests/testCucumberTestsInParallel.js
index ca6a7ae3..f34c9702 100644
--- a/test/cucumber-integration-tests/testCucumberTestsInParallel.js
+++ b/test/cucumber-integration-tests/testCucumberTestsInParallel.js
@@ -5,17 +5,17 @@ const commandMocks = require('../lib/command-mocks.js');
 const common = require('../common.js');
 const MockServer = require('../lib/mockserver.js');
 
-describe('Cucumber integration - parallel running single formatter', function() {
-  beforeEach(function(done) {
+describe('Cucumber integration - parallel running single formatter', function () {
+  beforeEach(function (done) {
     this.server = MockServer.init(null, {port: 10190});
     this.server.on('listening', () => done());
   });
 
-  afterEach(function(done) {
+  afterEach(function (done) {
     Globals.afterEach.call(this, done);
   });
 
-  it('testCucumberSampleTests in parallel with single formatter', function() {
+  it('testCucumberSampleTests in parallel with single formatter', function () {
     const source = [
       path.join(__dirname, './sample_cucumber_tests/parallel/testSample.js')
     ];
@@ -41,7 +41,7 @@ describe('Cucumber integration - parallel running single formatter', function()
       });
   });
 
-  it('testCucumberSampleTests in parallel with multiple step definition files', function() {
+  it('testCucumberSampleTests in parallel with multiple step definition files', function () {
 
     commandMocks.elementText('5cc459b8-36a8-3042-8b4a-258883ea642b', 'xx');
 
@@ -56,6 +56,7 @@ describe('Cucumber integration - parallel running single formatter', function()
       parallel: true,
       verbose: true,
       timeout: 10,
+      env: 'chrome',
       silent: false,
       tags: ['not @fail'],
       format: 'progress',
@@ -71,4 +72,36 @@ describe('Cucumber integration - parallel running single formatter', function()
         assert.strictEqual(errorOrFailed, false);
       });
   });
-});
\ No newline at end of file
+
+  it('testCucumberSampleTests in parallel environments with multiple step definition files', function () {
+
+    commandMocks.elementText('5cc459b8-36a8-3042-8b4a-258883ea642b', 'xx');
+
+    const source = [
+      path.join(__dirname, './sample_cucumber_tests/parallelWithMultipleDefinition')
+    ];
+
+    const {runTests} = common.require('index.js');
+
+    return runTests({
+      source,
+      parallel: true,
+      verbose: true,
+      timeout: 10,
+      env: 'chrome,firefox',
+      silent: false,
+      tags: ['not @fail'],
+      format: 'progress',
+      config: path.join(__dirname, '../extra/cucumber-config-parallel.js'),
+      'format-options': '',
+      ['retry-interval']: 5,
+      ['persist-globals']: true,
+      ['webdriver-host']: 'localhost',
+      ['start-process']: false,
+      ['webdriver-port']: 10190
+    }, {})
+      .then(errorOrFailed => {
+        assert.strictEqual(errorOrFailed, false);
+      });
+  });
+});
diff --git a/test/extra/cucumber-config-parallel.js b/test/extra/cucumber-config-parallel.js
index 302ea421..16badba9 100644
--- a/test/extra/cucumber-config-parallel.js
+++ b/test/extra/cucumber-config-parallel.js
@@ -26,6 +26,19 @@ module.exports = {
       feature_path: path.join(__dirname, '../cucumber-integration-tests/sample_cucumber_tests/parallel/sample.feature')
     }
   },
+
+  test_settings: {
+    chrome: {
+      desiredCapabilities: {
+        browserName: 'chrome'
+      }
+    },
+    firefox: {
+      desiredCapabilities: {
+        browserName: 'firefox'
+      }
+    }
+  },
   output: false,
   silent: false
-}
\ No newline at end of file
+};
\ No newline at end of file
diff --git a/test/src/api/commands/web-element/testGetRect.js b/test/src/api/commands/web-element/testGetRect.js
index 17e52353..d3fb6493 100644
--- a/test/src/api/commands/web-element/testGetRect.js
+++ b/test/src/api/commands/web-element/testGetRect.js
@@ -38,6 +38,30 @@ describe('element().getRect() command', function () {
     assert.deepStrictEqual(resultValue, {height: 34, width: 443, x: 356, y: 381.5});
   });
 
+  it('test .element().rect()', async function() {
+    MockServer.addMock({
+      url: '/session/13521-10219-202/element/0/rect',
+      method: 'GET',
+      response: JSON.stringify({
+        value: {height: 34, width: 443, x: 356, y: 381.5}
+      })
+    }, true);
+
+    const resultPromise = this.client.api.element('#signupSection').rect();
+    assert.strictEqual(resultPromise instanceof Element, false);
+    assert.strictEqual(typeof resultPromise.find, 'undefined');
+
+    assert.strictEqual(resultPromise instanceof Promise, false);
+    assert.strictEqual(typeof resultPromise.then, 'function');
+
+    const result = await resultPromise;
+    assert.strictEqual(result instanceof WebElement, false);
+    assert.deepStrictEqual(result, {height: 34, width: 443, x: 356, y: 381.5});
+
+    const resultValue = await resultPromise.value;
+    assert.deepStrictEqual(resultValue, {height: 34, width: 443, x: 356, y: 381.5});
+  });
+
   it('test .element().getSize()', async function() {
     MockServer.addMock({
       url: '/session/13521-10219-202/element/0/rect',
@@ -133,4 +157,5 @@ describe('element().getRect() command', function () {
     const resultValue = await resultPromise.value;
     assert.deepStrictEqual(resultValue, {height: 34, width: 443, x: 356, y: 381.5});
   });
+
 });
diff --git a/test/src/api/commands/web-element/testIsVisible.js b/test/src/api/commands/web-element/testIsVisible.js
index c1ba6c97..ed2fddf5 100644
--- a/test/src/api/commands/web-element/testIsVisible.js
+++ b/test/src/api/commands/web-element/testIsVisible.js
@@ -41,6 +41,33 @@ describe('element().isVisible() command', function() {
     assert.strictEqual(elementId, '0');
   });
 
+  it('test .element().isDisplayed() displayed', async function() {
+    let elementId;
+
+    MockServer.addMock({
+      url: '/session/13521-10219-202/execute/sync',
+      method: 'POST',
+      response: JSON.stringify({
+        value: true
+      }),
+      onRequest(_, requestData) {
+        elementId = requestData.args[0]['element-6066-11e4-a52e-4f735466cecf'];
+      }
+    }, true);
+
+    const resultPromise = this.client.api.element('#signupSection').isDisplayed();
+    assert.strictEqual(resultPromise instanceof Element, false);
+    assert.strictEqual(typeof resultPromise.find, 'undefined');
+
+    assert.strictEqual(resultPromise instanceof Promise, false);
+    assert.strictEqual(typeof resultPromise.then, 'function');
+
+    const result = await resultPromise;
+    assert.strictEqual(result instanceof WebElement, false);
+    assert.strictEqual(result, true);
+    assert.strictEqual(elementId, '0');
+  });
+
   it('test .element().isVisible() not displayed', async function() {
     let elementId;
 
@@ -68,6 +95,33 @@ describe('element().isVisible() command', function() {
     assert.strictEqual(elementId, '0');
   });
 
+  it('test .element().isDisplayed() not displayed', async function() {
+    let elementId;
+
+    MockServer.addMock({
+      url: '/session/13521-10219-202/execute/sync',
+      method: 'POST',
+      response: JSON.stringify({
+        value: false
+      }),
+      onRequest(_, requestData) {
+        elementId = requestData.args[0]['element-6066-11e4-a52e-4f735466cecf'];
+      }
+    }, true);
+
+    const resultPromise = this.client.api.element('#signupSection').isDisplayed();
+    assert.strictEqual(resultPromise instanceof Element, false);
+    assert.strictEqual(typeof resultPromise.find, 'undefined');
+
+    assert.strictEqual(resultPromise instanceof Promise, false);
+    assert.strictEqual(typeof resultPromise.then, 'function');
+
+    const result = await resultPromise;
+    assert.strictEqual(result instanceof WebElement, false);
+    assert.strictEqual(result, false);
+    assert.strictEqual(elementId, '0');
+  });
+
   it('test .element().find().isVisible()', async function() {
     let elementId;
 
diff --git a/types/tests/webElement.test-d.ts b/types/tests/webElement.test-d.ts
index 78edaa90..ed24c4f5 100644
--- a/types/tests/webElement.test-d.ts
+++ b/types/tests/webElement.test-d.ts
@@ -142,9 +142,12 @@ describe('new element() api', function () {
     expectType<ElementValue<string | null>>(elem.getValue());
     expectType<ElementValue<boolean>>(elem.isEnabled());
     expectType<ElementValue<boolean>>(elem.isVisible());
+    expectType<ElementValue<boolean>>(elem.isDisplayed());
 
     expectType<ElementValue<ScopedElementRect>>(elem.getRect());
+    expectType<ElementValue<ScopedElementRect>>(elem.rect());
     expectType<ElementValue<ScopedElementRect>>(elem.getSize());
+    expectType<ElementValue<ScopedElementRect>>(elem.getLocation());
 
     expectType<ElementValue<string>>(elem.getAccessibleName());
     expectType<ElementValue<string>>(elem.getAriaRole());