Repository: nightwatchjs/nightwatch
Pull request #2637 (2021-04-13 13:30:11)

Issue/2618 element timeout
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/_loaders/_base-loader.js b/lib/api/_loaders/_base-loader.js
index 0cd87d22..b8ba8552 100644
--- a/lib/api/_loaders/_base-loader.js
+++ b/lib/api/_loaders/_base-loader.js
@@ -174,6 +174,9 @@ class BaseLoader extends EventEmitter {
 
   validateMethod(parent) {
     let namespace = this.getTargetNamespace(parent);
+    if (Array.isArray(namespace) && namespace.length > 0) {
+      namespace = BaseLoader.unflattenNamespace(this.api, namespace.slice());
+    }
 
     if (this.nightwatchInstance.isApiMethodDefined(this.commandName, namespace)) {
       throw new Error(`The ${this.type} ${this.namespace || ''}.${this.commandName}() is already defined.`);
diff --git a/lib/api/assertions/_assertionInstance.js b/lib/api/assertions/_assertionInstance.js
index 7f198b6d..8b2b4ae7 100644
--- a/lib/api/assertions/_assertionInstance.js
+++ b/lib/api/assertions/_assertionInstance.js
@@ -19,6 +19,8 @@ class AssertionInstance {
     this.fileName = fileName;
     this.__negate = options.negate || false;
     this.__commandResult = null;
+    this.retryAssertionTimeout = Utils.isObject(args[0]) ? args[0].timeout : undefined;
+    this.rescheduleInterval = Utils.isObject(args[0]) ? args[0].retryInterval : undefined;
 
     EventEmitter.prototype.constructor.call(this);
   }
diff --git a/lib/api/element-commands/_waitFor.js b/lib/api/element-commands/_waitFor.js
index 3d91e03e..3a58e4f7 100644
--- a/lib/api/element-commands/_waitFor.js
+++ b/lib/api/element-commands/_waitFor.js
@@ -1,6 +1,5 @@
 const Utils = require('../../utils');
 const {AssertionRunner} = require('../../assertion');
-const LocateStrategy = require('../../element').LocateStrategy;
 const ElementCommand = require('../../element').Command;
 
 /*!
diff --git a/lib/api/index.js b/lib/api/index.js
index 33db8ced..e0e1ae11 100644
--- a/lib/api/index.js
+++ b/lib/api/index.js
@@ -229,9 +229,9 @@ class ApiLoader {
     fileName,
     parent,
     namespace = [],
-    abortOnFailure,
-    isProtocolCommand,
-    isElementCommand,
+    abortOnFailure = false,
+    isProtocolCommand = false,
+    isElementCommand = false,
     Loader = CommandLoader
   }) {
     const loader = new Loader(this.nightwatchInstance);
@@ -253,14 +253,46 @@ class ApiLoader {
 
   __loadCustomObjectsSync({parent = null, Loader = CommandLoader, namespaces, sourcePath}) {
     const dirPathArr = ApiLoader.adaptCustomPath(sourcePath);
+    const commandFiles = [];
 
     dirPathArr.forEach(dirPath => this.__loadCommandsSync({
       parent,
-      Loader,
       dirPath,
       isUserDefined: true,
-      namespacesObj: namespaces
+      namespacesObj: namespaces,
+      Loader,
+      loadAction(opts) {
+        commandFiles.push(opts);
+      }
     }));
+
+    const hasCorrespondingJsFile = (parsedResource) => {
+      const jsFile = path.join(parsedResource.dir, `${parsedResource.name}${Utils.jsFileExt}`);
+
+      const entry = commandFiles.find(({dirPath, fileName}) => {
+        return path.join(dirPath, fileName) === jsFile;
+      });
+
+      return !!entry;
+    };
+
+    const commandFilesProcessed = commandFiles.reduce((prev, opts) => {
+      const {dirPath, fileName} = opts;
+      const fullPath = path.join(dirPath, fileName);
+      const parsedResource = path.parse(fullPath);
+      const isTypeScriptFile = parsedResource.ext === Utils.tsFileExt;
+
+      // ignore `.ts` files if a `.js` has already been loaded
+      if (isTypeScriptFile && hasCorrespondingJsFile(parsedResource)) {
+        return prev;
+      }
+
+      prev.push(opts);
+
+      return prev;
+    }, []);
+
+    commandFilesProcessed.forEach(opts => this.addCommandDefinitionSync(opts));
   }
 
   __loadCommandsSync({
@@ -272,7 +304,8 @@ class ApiLoader {
     isProtocolCommand = false,
     isElementCommand = false,
     isUserDefined = false,
-    Loader = CommandLoader
+    Loader = CommandLoader,
+    loadAction = this.addCommandDefinitionSync.bind(this)
   }) {
     if (namespacesObj) {
       Object.keys(namespacesObj).forEach((ns) => this.__loadCommandsSync({
@@ -286,7 +319,7 @@ class ApiLoader {
       }));
     } else {
       Utils.readFolderRecursively(dirPath, [], (dirPath, fileName, namespace) => {
-        this.addCommandDefinitionSync({
+        loadAction.call(this, {
           dirPath,
           fileName,
           parent,
diff --git a/lib/utils/index.js b/lib/utils/index.js
index 3e0af318..d163c9fa 100644
--- a/lib/utils/index.js
+++ b/lib/utils/index.js
@@ -403,6 +403,8 @@ class Utils {
   static readFolderRecursively(sourcePath, namespace = [], loadFn) {
     const resources = fs.readdirSync(sourcePath);
 
+    resources.sort(); // makes the list predictable
+
     resources.forEach(resource => {
       const isFolder = fs.lstatSync(path.join(sourcePath, resource)).isDirectory();
 


Test patch:
diff --git a/test/extra/commands/typescript/wait.js b/test/extra/commands/typescript/wait.js
new file mode 100644
index 00000000..c7609ecb
--- /dev/null
+++ b/test/extra/commands/typescript/wait.js
@@ -0,0 +1,7 @@
+// NOTE: this file represents a compiled version of `wait.ts` generated by `tsc`.
+
+module.exports.command = function(timeout = 0) {
+  return this
+    .perform(() => console.log(`Waiting ${timeout}ms`))
+    .pause(timeout);
+};
diff --git a/test/extra/commands/typescript/wait.ts b/test/extra/commands/typescript/wait.ts
new file mode 100644
index 00000000..8c2adaaf
--- /dev/null
+++ b/test/extra/commands/typescript/wait.ts
@@ -0,0 +1,10 @@
+// NOTE: by default nightwatch does not know how to execute .ts files hence
+// additional steps are required. For example compiling them to .js before
+// running nightwatch using `tsc`. This will create a second file, wait.js
+// in this case, that is executable by nightwatch (NodeJS).
+
+export function command(timeout = 0) {
+  return this
+    .perform(() => console.log(`Waiting ${timeout}ms`))
+    .pause(timeout);
+}
diff --git a/test/lib/globals.js b/test/lib/globals.js
index c62ceae9..b8326229 100644
--- a/test/lib/globals.js
+++ b/test/lib/globals.js
@@ -326,6 +326,8 @@ module.exports.assertion = function(assertionName, api, {
 
         if (assertArgs) {
           assert.deepStrictEqual(assertionInstance.args, args);
+          assert.deepStrictEqual(assertionInstance.retryAssertionTimeout, undefined);
+          assert.deepStrictEqual(assertionInstance.rescheduleInterval, undefined);
         }
 
         if (assertFailure) {
diff --git a/test/sampletests/typescript/sample.ts b/test/sampletests/typescript/sample.ts
index 1e96556a..ca3641f2 100644
--- a/test/sampletests/typescript/sample.ts
+++ b/test/sampletests/typescript/sample.ts
@@ -1,6 +1,7 @@
 module.exports = {
   demoTest: function(client: any) {
     client.url('http://localhost')
+      .typescript.wait(10)
       .assert.elementPresent('#weblogin');
   },
 
diff --git a/test/src/api/assertions/testVisible.js b/test/src/api/assertions/testVisible.js
index 5f9afb4d..b570ab40 100644
--- a/test/src/api/assertions/testVisible.js
+++ b/test/src/api/assertions/testVisible.js
@@ -87,6 +87,26 @@ describe('assert.visible', function () {
     });
   });
 
+  it('visible 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(), 'visible');
+        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 visible'), message);
+        assert.strictEqual(failure, false);
+      }
+    });
+  });
+  
   it('visible assertion failed', function () {
     return assertionTest({
       args: ['.test_element'],
diff --git a/test/src/runner/testRunnerTypeScript.js b/test/src/runner/testRunnerTypeScript.js
index ec026f67..53d8a1b9 100644
--- a/test/src/runner/testRunnerTypeScript.js
+++ b/test/src/runner/testRunnerTypeScript.js
@@ -31,17 +31,23 @@ describe('testRunnerTypeScript', function() {
     process.removeAllListeners('unhandledRejection');
   });
 
+  this.timeout(5000);
+
   it('testRunSimple', function() {
     let testsPath = path.join(__dirname, '../../sampletests/typescript');
     let globals = {
-      reporter(results) {
-        assert.ok('sample' in results.modules);
-        assert.ok('demoTest' in results.modules['sample'].completed);
-        assert.strictEqual(results.modules['sample'].modulePath, path.join(__dirname, '../../sampletests/typescript/sample.ts'));
+      reporter({lastError, errmessages, modules}) {
+        if (lastError) {
+          throw lastError;
+        }
 
-        if (results.lastError) {
-          throw results.lastError;
+        if (errmessages.length) {
+          throw new Error(errmessages[0]);
         }
+
+        assert.ok('sample' in modules);
+        assert.ok('demoTest' in modules['sample'].completed);
+        assert.strictEqual(modules['sample'].modulePath, path.join(__dirname, '../../sampletests/typescript/sample.ts'));
       }
     };
 
@@ -51,9 +57,11 @@ describe('testRunnerTypeScript', function() {
         version2: true,
         start_process: true
       },
+      custom_commands_path: path.join(__dirname, '../../extra/commands'),
       output: false,
+      silent: false,
       persist_globals: true,
-      globals: globals,
+      globals,
       output_folder: false
     });
   });