Repository: nightwatchjs/nightwatch (js)

Issue:
CDP does not reset the connection after a test session ends
### Description of the bug/issue

When running multiple test suits each using `registerBasicAuth`, only the first test suit works.

### Steps to reproduce

1. use `registerBasicAuth` in 2 different test files
2. run all test files with nightwatch

### Sample test

```node
## Test File 1
describe('1: Test basic auth', function () {

    test('First', function (browser) {
        browser
            .registerBasicAuth('user', 'pass')
            .navigateTo('https://example.ch')
            .pause(4000)
            .assert.titleContains('Title');
    });

    test('First Another', function (browser) {
        browser
            .navigateTo('https://example.ch/underpage')
            .pause(4000)
            .waitForElementVisible('body');
    });
});

## Test File 2
describe('2: Test basic auth', function () {

    test('Second', function (browser) {
        browser
            .registerBasicAuth('user', 'pass')
            .navigateTo('https://example.ch/contact')
            .pause(4000)
            .assert.titleContains('contact');
    });

    test('Second Another', function (browser) {
        browser
            .navigateTo('https://example/events')
            .pause(4000)
            .waitForElementVisible('body');
    });
});
```


### Command to run

```bash
npx nightwatch ./basic-auth
```


### Verbose Output

```fundamental
[2: Test basic auth] Test Suite
──────────────────────────────────────────────────────────────
⠋ Starting ChromeDriver on port 9515...
 Starting ChromeDriver with server_path=<project-path>/node_modules/chromedriver/lib/chromedriver/chromedriver...
 ChromeDriver process closed.
   Request POST /session  
   {
     desiredCapabilities: {
       browserName: 'chrome',
       'goog:chromeOptions': { w3c: false, args: [ '--no-sandbox', '--window-size=1920,1080' ] },
       name: '2: Test basic auth'
     },
     capabilities: {
       alwaysMatch: {
         browserName: 'chrome',
         'goog:chromeOptions': {
           w3c: false,
           args: [ '--no-sandbox', '--window-size=1920,1080' ]
         }
       }
     }
⠧ Starting ChromeDriver on port 9515...
   Response 200 POST /session (584ms)
   {
     sessionId: '6af5e2832229e552b0394eac92f88181',
     status: 0,
     value: {
       acceptInsecureCerts: false,
       acceptSslCerts: false,
       browserConnectionEnabled: false,
       browserName: 'chrome',
       chrome: {
         chromedriverVersion: '106.0.5249.61 (511755355844955cd3e264779baf0dd38212a4d0-refs/branch-heads/5249@{#569})',
         userDataDir: '/tmp/.com.google.Chrome.2bdBqR'
       },
       cssSelectorsEnabled: true,
       databaseEnabled: false,
       'goog:chromeOptions': { debuggerAddress: 'localhost:34971' },
       handlesAlerts: true,
       hasTouchScreen: false,
       javascriptEnabled: true,
       locationContextEnabled: true,
       mobileEmulationEnabled: false,
       nativeEvents: true,
       networkConnectionEnabled: false,
       pageLoadStrategy: 'normal',
       platform: 'Linux',
       proxy: {},
       rotatable: false,
       setWindowRect: true,
       strictFileInteractability: false,
       takesHeapSnapshot: true,
       takesScreenshot: true,
       timeouts: { implicit: 0, pageLoad: 300000, script: 30000 },
       unexpectedAlertBehaviour: 'ignore',
       version: '107.0.5304.68',
       webStorageEnabled: true,
       'webauthn:extension:credBlob': true,
       'webauthn:extension:largeBlob': true,
       'webauthn:virtualAuthenticators': true
     }
ℹ Connected to ChromeDriver on port 9515 (619ms).
  Using: chrome (107.0.5304.68) on LINUX.

 Received session with ID: 6af5e2832229e552b0394eac92f88181

 → Running [before]:
 → Completed [before].
```


### Nightwatch Configuration

```node
const chromedriver = require("chromedriver");
const geckodriver = require("geckodriver");

require("dotenv").config();

module.exports = {
    src_folders: ["test-folder"],
    page_objects_path: ["pages"],
    custom_commands_path: "./commands",
    test_workers: false,
    start_session: true,

    // reporter output
    output_folder: './reports',
    screenshots: {
        enabled: true,
        path: './screenshots',
        on_error: true,
        on_failure: true
    },
    log_screenshot_data: true,

    test_settings: {
        default: {
            desiredCapabilities: {
                browserName: "chrome",
                "goog:chromeOptions": {
                    w3c: false,
                    args: ["--no-sandbox", "--window-size=1920,1080"]
                },
            },
            webdriver: {
                start_process: true,
                port: 9515,
                server_path: chromedriver.path
            },
        },
        firefox: {
            desiredCapabilities: {
                browserName: 'firefox'
            },
            webdriver: {
                start_process: true,
                port: 4445,
                server_path: geckodriver.path
            }
        }
    }
};
```


### Nightwatch.js Version

3.4.1

### Node Version

16

### Browser

Chrome: 106.0.1

### Operating System

Linux 5.15.74-1-lts

### Additional Information

The independent test files work fine if called directly. But if a whole folder is called only the first one works as excpected

Pull request description:
Fixes/3455 reset cdp connection on session end
## Changes
- reset cdp connection after the test session ends.


## Impacts
- fixes #3455 

Patch:
diff --git a/lib/transport/selenium-webdriver/index.js b/lib/transport/selenium-webdriver/index.js
index a039c2e3..fac23ca2 100644
--- a/lib/transport/selenium-webdriver/index.js
+++ b/lib/transport/selenium-webdriver/index.js
@@ -7,6 +7,7 @@ const {Logger, isObject, IosSessionNotCreatedError, AndroidConnectionError} = re
 const httpClient = require('./httpclient.js');
 const Session = require('./session.js');
 const BaseTransport = require('../');
+const CDP = require('./cdp.js');
 const {colors} = Logger;
 const {isErrorResponse, checkLegacyResponse, throwDecodedError, WebDriverError} = error;
 
@@ -187,7 +188,7 @@ class Transport extends BaseTransport {
 
   async sessionFinished(reason) {
     this.emit('session:finished', reason);
-
+    CDP.resetConnection();
     await this.closeDriver();
   }
 


Test patch:
diff --git a/test/apidemos/cdp/registerAuth.js b/test/apidemos/cdp/registerAuth.js
new file mode 100644
index 00000000..b2d096ac
--- /dev/null
+++ b/test/apidemos/cdp/registerAuth.js
@@ -0,0 +1,6 @@
+describe('cdp tests', function() {
+  it('register basic auth', function() {
+    browser.registerBasicAuth('admin', 'admin')
+      .navigateTo('http://localhost');
+  });
+});
\ No newline at end of file
diff --git a/test/apidemos/cdp/registerAuth2.js b/test/apidemos/cdp/registerAuth2.js
new file mode 100644
index 00000000..b2d096ac
--- /dev/null
+++ b/test/apidemos/cdp/registerAuth2.js
@@ -0,0 +1,6 @@
+describe('cdp tests', function() {
+  it('register basic auth', function() {
+    browser.registerBasicAuth('admin', 'admin')
+      .navigateTo('http://localhost');
+  });
+});
\ No newline at end of file
diff --git a/test/lib/command-mocks.js b/test/lib/command-mocks.js
index 6ec31edc..57ba2708 100644
--- a/test/lib/command-mocks.js
+++ b/test/lib/command-mocks.js
@@ -448,7 +448,7 @@ module.exports = {
           sessionId,
           capabilities: {
             acceptInsecureCerts: false,
-            browserName: 'firefox',
+            browserName,
             browserVersion: '65.0.1'
           }
         }
diff --git a/test/src/apidemos/cdp/testCdpCommands.js b/test/src/apidemos/cdp/testCdpCommands.js
new file mode 100644
index 00000000..90e45ca6
--- /dev/null
+++ b/test/src/apidemos/cdp/testCdpCommands.js
@@ -0,0 +1,81 @@
+const path = require('path');
+const assert = require('assert');
+const MockServer = require('../../../lib/mockserver.js');
+const Mocks = require('../../../lib/command-mocks');
+
+const mockery = require('mockery');
+const common = require('../../../common.js');
+const {settings} = common;
+const NightwatchClient = common.require('index.js');
+
+describe('cdp commands test', function() {
+  beforeEach(function(done) {
+    mockery.enable({useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false});
+    this.server = MockServer.init();
+    this.server.on('listening', () => {
+      done();
+    });
+  });
+
+  afterEach(function(done) {
+    mockery.deregisterAll();
+    mockery.resetCache();
+    mockery.disable();
+    this.server.close(function() {
+      done();
+    });
+  });
+
+  it('reset cdp connection after each session', function() {
+    const testsPath = [path.join(__dirname, '../../../apidemos/cdp')];
+    let resetConnectionCalled = false;
+
+    mockery.registerMock('./cdp.js', {
+      getConnection: function(...args) {
+        return Promise.resolve();
+      },
+      resetConnection: function() {
+        resetConnectionCalled = true;
+      }
+    });
+
+    Mocks
+      .createNewW3CSession({
+        persist: true,
+        browserName: 'chrome',
+        postdata: {
+          capabilities: {firstMatch: [{}], alwaysMatch: {browserName: 'chrome', 'goog:chromeOptions': {}}}
+        }
+      })
+      .navigateTo({url: 'http://localhost', persist: true});
+
+   
+
+    const globals = {
+      calls: 0,
+      waitForConditionPollInterval: 50,
+      waitForConditionTimeout: 120,
+      retryAssertionTimeout: 1000,
+
+
+      reporter(results) {
+        assert.strictEqual(resetConnectionCalled, true);
+        if (results.lastError) {
+          throw results.lastError;
+        }
+      }
+    };
+
+    return NightwatchClient.runTests(testsPath, settings({
+      desiredCapabilities: {
+        browserName: 'chrome'
+      },
+      selenium_host: null,
+      output: false,
+      skip_testcases_on_fail: false,
+      globals
+    }));
+  });
+
+  
+});