Repository: nightwatchjs/nightwatch
Pull request #2641 (2021-04-14 12:41:58)

custom message with only time(%d) placeholder #2532
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/expect/assertions/element/_element-assertion.js b/lib/api/expect/assertions/element/_element-assertion.js
index 8dcf113b..cdd5e475 100644
--- a/lib/api/expect/assertions/element/_element-assertion.js
+++ b/lib/api/expect/assertions/element/_element-assertion.js
@@ -31,7 +31,7 @@ class ExpectElement extends BaseAssertion {
       selector = this.element.toString();
     }
 
-    this.message = Utils.format(this.message, selector);
+    this.message = Utils.format(this.message, selector, this.elapsedTime);
 
     super.formatMessage();
   }
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..52ba08b3 100644
--- a/lib/utils/index.js
+++ b/lib/utils/index.js
@@ -174,29 +174,21 @@ class Utils {
    * @param f
    * @returns {string}
    */
-  static format(f) {
-    let i = 1;
-    let args = arguments;
-    let len = args.length;
-
-    return String(f).replace(formatRegExp, function(x) {
-      if (x === '%%') {
+  static format(message, selector, timeMS) {
+    return String(message).replace(formatRegExp, function(exp) {
+      if (exp === '%%') {
         return '%';
       }
 
-      if (i >= len) {
-        return x;
-      }
-
-      switch (x) {
+      switch (exp) {
         case '%s':
-          return String(args[i++]);
+          return String(selector);
 
         case '%d':
-          return Number(args[i++]);
+          return Number(timeMS);
 
         default:
-          return x;
+          return exp;
       }
     });
   }
@@ -403,6 +395,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/api/commands/testWaitForElementPresent.js b/test/src/api/commands/testWaitForElementPresent.js
index ed4cc446..96333160 100644
--- a/test/src/api/commands/testWaitForElementPresent.js
+++ b/test/src/api/commands/testWaitForElementPresent.js
@@ -64,6 +64,23 @@ describe('waitForElementPresent', function() {
     }).catch(done);
   });
 
+  it('client.waitForElementPresent() failure with custom time message',function(done){
+    this.client.api.globals.waitForConditionPollInterval=10;
+    this.client.api.waitForElementPresent('.weblogin', 15, function callback(result,instance){
+      assert.strictEqual(instance.message, 'Element .weblogin found in 15 milliseconds')
+    }, 'Element %s found in %d milliseconds');
+
+    this.client.start(function(err) {
+      assert.ok(err instanceof Error);
+      if (err.name != 'NightwatchAssertError') {
+        done(err);
+      } else {
+        done();
+      }
+    }).catch(done);
+
+  })
+
   it('client.waitForElementPresent() with custom message and no params', function(done) {
     this.client.api.globals.waitForConditionPollInterval = 10;
 
diff --git a/test/src/api/commands/testWaitForElementVisible.js b/test/src/api/commands/testWaitForElementVisible.js
index fe54221c..1a533ac0 100644
--- a/test/src/api/commands/testWaitForElementVisible.js
+++ b/test/src/api/commands/testWaitForElementVisible.js
@@ -94,7 +94,7 @@ describe('waitForElementVisible', function() {
     this.client.api.waitForElementVisible('#weblogin', function callback(result, instance) {
       commandInstance = instance;
       assert.strictEqual(instance.message, 'Test message <#weblogin> and a global 15 ms.');
-    }, 'Test message <%s> and a global %s ms.');
+    }, 'Test message <%s> and a global %d ms.');
 
     return this.client.start(function(err) {
       if (!err) {
@@ -111,6 +111,39 @@ describe('waitForElementVisible', function() {
     });
   });
 
+  it('client.waitForElementVisible() fail with global timeout default and custom message with only time placeholder', function () {
+    MockServer.addMock({
+      url: '/wd/hub/session/1352110219202/element/0/displayed',
+      method: 'GET',
+      response: JSON.stringify({
+        sessionId: '1352110219202',
+        status: 0,
+        value: false
+      })
+    });
+
+    this.client.api.globals.waitForConditionTimeout = 15;
+    this.client.api.globals.waitForConditionPollInterval = 10;
+    this.client.api.waitForElementVisible('#weblogin', function callback(result, instance) {
+      commandInstance = instance;
+      assert.strictEqual(instance.message, 'Test message with a global 15 ms.');
+    }, 'Test message with a global %d ms.');
+
+    return this.client.start(function(err) {
+      if (!err) {
+        throw new Error('Expected error but got none');
+      }
+
+      if (err.name === 'NightwatchAssertError') {
+        assert.strictEqual(err.message, `Test message with a global 15 ms. - expected "visible" but got: "not visible" (${commandInstance.elapsedTime}ms)`);
+
+        return;
+      }
+
+      throw err;
+    });
+  });
+
   it('client.waitForElementVisible() StaleElementReference error', function () {
     MockServer
       .addMock({
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
     });
   });