Repository: nightwatchjs/nightwatch (js)

Issue:
V2 - Error `TypeError: Cannot read property 'toLowerCase' of undefined at new Promise (<anonymous>)`  when running tests with AWS device farm settings
## Describe the bug
I'm trying to run tests on AWS device farm after upgrading to Nightwatch v2 but getting this error 
`TypeError: Cannot read property 'toLowerCase' of undefined
       at new Promise (<anonymous>)`
The test is running when adding other configuration (BrowserStack & local chrome webdriver)

## Sample test
<details><summary>sampleTest.js</summary><p>
<!-- browsers demand the next line be empty -->

```js
describe('Demo test Ecosia.org', function() {
  test('search for nightwatch', function(browser) {
    browser
      .url('https://www.ecosia.org/')
      .waitForElementVisible('body')
      .assert.titleContains('Ecosia')
      .assert.visible('input[type=search]')
      .sendKeys('input[type=search]', 'nightwatch')
      .assert.visible('button[type=submit]')
      .click('button[type=submit]')
      .assert.containsText('.mainline-results', 'Nightwatch.js')
      .end();
  })
});
```
</p></details>

**Run with command**
<!-- Include the command used to run the test, if applicable. -->

```sh
$ nightwatch Ecosia.js --verbose
```

### Verbose output
<details><summary>debug.log</summary><p>
<!-- browsers demand the next line be empty -->

```txt
No output
```
</p></details>


## Configuration
<details><summary>nightwatch.json</summary><p>
<!-- browsers demand the next line be empty -->

<!-- Please paste your nightwatch.json or nightwatch.conf.js here; make sure to leave out any sensitive details -->

```js
{
  "src_folders": "./tests",
  "page_objects_path": [
    "./page_object"
  ],
  "globals_path": "globals.js",
  "webdriver": {
    "keep_alive": true
  },
  "custom_commands_path": [
    "./lib/custom_commands",
    "./node_modules/nightwatch-xhr/es5/commands"
  ],
  "custom_assertions_path": [
    "./node_modules/nightwatch-xhr/es5/assertions"
  ],
  "test_workers": {
    "enabled": false,
    "workers": 0
  },
  "test_settings": {
    "default": {
      "selenium": {
        "start_process": false,
        "host": "testgrid-devicefarm.us-west-2.amazonaws.com",
        "default_path_prefix": "generated from aws device farm sdk",
        "port": 443
      },
      "skip_testcases_on_fail": false,
      "silent": true,
      "exclude": [
        "tests/*sample*.js"
      ],
      "request_timeout_options": {
        "timeout": 180000,
        "retry_attempts": 0
      },
      "output_folder": false,
      "end_session_on_fail": false,
      "desiredCapabilities": {
        "browserName": "chrome",
        "resolution": "1920x1080",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      },
      "capabilities": {}
    }
  },
  "live_output": true,
  "detailed_output": true,
  "test_runner": {
    "type": "default",
    "options": {
      "bail": "false",
      "retries": 0
    }
  }
}
```
</p></details>

## Your Environment
<!--- Include the relevant details your environment -->

| Executable | Version |
| ---: | :--- |
| `nightwatch --version` | 2.0.0-beta.1|
| `npm --version`  | 6.14.15|
| `node --version` | 14.18.0|

| Browser driver | Version |
| --- | --- |
| Chrome | Latest |

Pull request:
Fix #2955
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.

- [x] Create a new branch from master (e.g. `features/my-new-feature` or `issue/123-my-bugfix`);
- [x] If you're fixing a bug also create an issue if one doesn't exist yet;
- [x] 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;
- [x] 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;
- [x] If your change is based on existing functionality please consider refactoring first. Pull requests that duplicate code will most likely be ignored;
- [x] Do not include changes that are not related to the issue at hand;
- [x] Follow the same coding style with regards to spaces, semicolons, variable naming etc.;
- [x] Always add unit tests - PRs without tests are most of the times ignored.


Patch:
diff --git a/lib/api/assertions/textEquals.js b/lib/api/assertions/textEquals.js
new file mode 100644
index 00000000..93f4f178
--- /dev/null
+++ b/lib/api/assertions/textEquals.js
@@ -0,0 +1,68 @@
+/**
+ * Check if an elements inner text equals the expected text
+ *
+ * @example
+ * 
+ * ```
+ *   this.demoTest = function (browser) {
+ *     browser.assert.textEquals('#main', 'The Night Watch');
+ *   };
+ * ```
+ * 
+ * @method textEquals 
+ * @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#element-properties).
+ * @param {string} expected text to match text.
+ * @param {string} [msg] Optional log message to display in the output. If missing, one is displayed by default.
+ * @api assertions
+ */
+
+const {setElementSelectorProps} = require('../../utils');
+
+exports.assertion = function(definition, expected, msg) {
+  this.options = {
+    elementSelector: true
+  };
+ 
+  this.formatMessage = function() {
+    const message = msg || `Testing if element %s ${this.negate ? 'doesn\'t equal %s' : 'equals %s'}`;
+ 
+    return {
+      message,
+      args: [this.elementSelector, `'${expected}'`]
+    };
+  };
+ 
+  this.expected = function() {
+    return this.negate ? `doesn't equal '${expected}'` : `equals '${expected}'`;
+  };
+ 
+  this.evaluate = function(value) {
+    if (typeof value != 'string') {
+      return false;
+    }
+
+    return value === expected;
+  };
+
+  this.failure = function(result) {
+    return result === false || result && result.status === -1;
+  };
+  
+  this.value = function(result) {
+    if (result.status === -1) {
+      return null;
+    }
+
+    return result.value;
+  };
+
+  this.actual = function(passed) {
+    return passed ? `equals '${expected}'` : `doesn't equal '${expected}'`;
+  };
+ 
+  this.command = function(callback) {
+    this.api.getText(setElementSelectorProps(definition, {
+      suppressNotFoundErrors: true
+    }), callback);
+  };
+};
\ No newline at end of file
diff --git a/lib/core/client.js b/lib/core/client.js
index 94ff566b..13058619 100644
--- a/lib/core/client.js
+++ b/lib/core/client.js
@@ -425,7 +425,7 @@ class NightwatchClient extends EventEmitter {
   }
 
   get initialCapabilities() {
-    if (isObject(this.settings.capabilities)) {
+    if (isObject(this.settings.capabilities) && Object.keys(this.settings.capabilities).length > 0) {
       return this.settings.capabilities;
     }
 
@@ -433,7 +433,7 @@ class NightwatchClient extends EventEmitter {
   }
 
   setInitialCapabilities(value) {
-    if (isObject(this.settings.capabilities)) {
+    if (isObject(this.settings.capabilities) && Object.keys(this.settings.capabilities).length > 0) {
       this.settings.capabilities = value;
     } else {
       this.settings.desiredCapabilities = value;
diff --git a/lib/transport/factory.js b/lib/transport/factory.js
index ee853abb..08992bfd 100644
--- a/lib/transport/factory.js
+++ b/lib/transport/factory.js
@@ -61,7 +61,7 @@ module.exports = class TransportFactory {
       browserName = Browser.SAFARI;
     } else if (argv.edge) {
       browserName = Browser.EDGE;
-    } else if (BrowsersLowerCase[browserName.toLowerCase()]) {
+    } else if (BrowsersLowerCase[browserName && browserName.toLowerCase()]) {
       browserName = BrowsersLowerCase[browserName.toLowerCase()];
     } else {
       const didYouMean = require('didyoumean');


Test patch:
diff --git a/test/src/api/assertions/testTextEquals.js b/test/src/api/assertions/testTextEquals.js
new file mode 100644
index 00000000..d9513f2c
--- /dev/null
+++ b/test/src/api/assertions/testTextEquals.js
@@ -0,0 +1,119 @@
+const assert = require('assert');
+const Globals = require('../../../lib/globals.js');
+
+describe('assert.textEquals', function () {
+  const assertionName = 'textEquals';
+  const api = 'getText';
+
+  function assertionTest(opts) {
+    return Globals.assertion(assertionName, api, opts);
+  }
+
+  it('textEquals assertion passed', function () {
+    return assertionTest({
+      args: ['.test_element', 'text result', 'Test message'],
+      commandResult: {
+        value: 'text result'
+      },
+      assertArgs: true,
+      assertMessage: true,
+      assertion({reporter, instance, failure}) {
+        assert.deepStrictEqual(instance.options, {elementSelector: true});
+        assert.strictEqual(failure, false);
+        assert.strictEqual(instance.getValue(), 'text result');
+        assert.strictEqual(instance.hasFailure(), false);
+      }
+    });
+  });
+
+  it('not.textEquals assertion passed', function () {
+    return assertionTest({
+      args: ['.test_element', 'text result', 'Test message'],
+      commandResult: {
+        value: 'other text'
+      },
+      negate: true,
+      assertion({reporter, instance, queueOpts, message}) {
+        assert.strictEqual(typeof err, 'undefined');
+        assert.strictEqual(queueOpts.negate, true);
+
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.strictEqual(instance.getValue(), 'other text');
+        assert.strictEqual(instance.getActual(), 'doesn\'t equal \'text result\'');
+        assert.strictEqual(instance.message, 'Test message');
+      }
+    });
+  });
+
+  it('not.textEquals assertion failed', function () {
+    return assertionTest({
+      args: ['.test_element', 'text result', 'Test message'],
+      commandResult: {
+        value: 'text result'
+      },
+      negate: true,
+      assertError: true,
+      assertion({instance, queueOpts, err}) {
+        assert.strictEqual(queueOpts.negate, true);
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.strictEqual(instance.getValue(), 'text result');
+        assert.strictEqual(instance.getActual(), 'equals \'text result\'');
+        assert.strictEqual(err.message, `Test message in 5ms - expected "doesn't equal 'text result'" but got: "equals 'text result'" (${instance.elapsedTime}ms)`);
+      }
+    });
+  });
+
+  it('textEquals assertion passed with selector object', function () {
+    return assertionTest({
+      args: [{selector: '.test_element'}, 'text result'],
+      commandResult: {
+        value: 'text result'
+      },
+      assertArgs: true,
+      assertResult: true,
+      assertion({instance, failure, message, err}) {
+        assert.ok(message.startsWith('Testing if element <.test_element> equals \'text result\''), message);
+        assert.deepStrictEqual(instance.options, {elementSelector: true});
+        assert.strictEqual(instance.getActual(), 'equals \'text result\'');
+        assert.strictEqual(instance.hasFailure(), false);
+        assert.ok(message.startsWith('Testing if element <.test_element> equals \'text result\''), message);
+        assert.strictEqual(failure, false);
+      }
+    });
+  });
+
+  it('textEquals assertion failed', function () {
+    return assertionTest({
+      args: ['.test_element', 'text result', 'Test message'],
+      commandResult: {
+        value: 'not_expected'
+      },
+      assertError: true,
+      assertResult: true,
+      assertion({instance, failure}) {
+        assert.strictEqual(instance.getActual(), 'doesn\'t equal \'text result\'');
+        assert.strictEqual(failure, 'Expected "equals \'text result\'" but got: "doesn\'t equal \'text result\'"');
+      }
+    });
+  });
+
+  it('textEquals assertion - element not found', function () {
+    return assertionTest({
+      args: ['.test_element', 'text result', 'Test message'],
+      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(), 'equals \'text result\'');
+        assert.strictEqual(instance.getValue(), null);
+        assert.strictEqual(failure, 'Expected "equals \'text result\'" but got: "element could not be located"');
+        assert.strictEqual(err.message, `Test message in 5ms - expected "equals 'text result'" but got: "element could not be located" (${instance.elapsedTime}ms)`);
+      }
+    });
+  });
+});
+
diff --git a/test/src/api/commands/element/testIsVisible.js b/test/src/api/commands/element/testIsVisible.js
index 66827cda..53704396 100644
--- a/test/src/api/commands/element/testIsVisible.js
+++ b/test/src/api/commands/element/testIsVisible.js
@@ -37,4 +37,24 @@ describe('isVisible', function() {
 
     this.client.start(done);
   });
+
+  it('client.isVisible()', function(done) {
+    MockServer.addMock({
+      url: '/wd/hub/session/1352110219202/element/0/displayed',
+      method: 'GET',
+      response: JSON.stringify({
+        sessionId: '1352110219202',
+        status: 0,
+        value: false
+      })
+    });
+
+    this.client.api.isVisible('css selector', '#weblogin', function callback(result) {
+      assert.strictEqual(result.value, false);
+    }).isVisible('#weblogin', function callback(result) {
+      assert.strictEqual(result.value, false);
+    });
+
+    this.client.start(done);
+  });
 });
diff --git a/test/src/core/testCreateSession.js b/test/src/core/testCreateSession.js
index 8d831697..a6ac54f3 100644
--- a/test/src/core/testCreateSession.js
+++ b/test/src/core/testCreateSession.js
@@ -338,4 +338,53 @@ describe('test Request With Credentials', function () {
       ]
     });
   });
+
+  it('Test blank object capabilities', async function () {
+    nock('http://localhost:10195')
+      .post('/wd/hub/session')
+      .reply(201, {
+        status: 0,
+        sessionId: '1352110219202',
+        value: {
+          browserName: 'chrome',
+          version: 'TEST',
+          platform: 'TEST'
+        }
+      });
+
+    let client = Nightwatch.createClient({
+      selenium_port: 10195,
+      silent: false,
+      output: false,
+      desiredCapabilities: {
+        browserName: 'chrome'
+      },
+      capabilities: {}
+    });
+
+    const result = await client.createSession();
+    assert.deepStrictEqual(client.transport.desiredCapabilities, {
+      browserName: 'chrome'
+    });
+    assert.deepStrictEqual(result, {
+      sessionId: '1352110219202',
+      capabilities: {
+        browserName: 'chrome', version: 'TEST', platform: 'TEST'
+      }
+    });
+  });
+
+  it('Test blank browserName', async function () {
+    assert.throws(function() {
+      let client = Nightwatch.createClient({
+        selenium_port: 10195,
+        silent: false,
+        output: false,
+        desiredCapabilities: {},
+        capabilities: {
+          alwaysMatch: {}
+        }
+      });
+    }, /Error: Unknown browser:/);
+  });
 });