webdriver | selenium session | close all windows | Search

The code defines an asynchronous function testDriver that imports a getClient module, sets up a web driver, navigates to Facebook, waits for 4 seconds, and then closes the driver. The function is exported as a module.

Run example

npm run import -- "webdriver test"

webdriver test


const getClient = importer.import("webdriver client")

async function testDriver() {
  let driver = await getClient()
  try {
    let facebook = 'https://www.facebook.com'

    await driver.get(facebook)

    await new Promise(resolve => setTimeout(resolve, 4000))
  } catch (e) {
    console.log(e)
  } finally {
    driver.quit()
  }
}

module.exports = testDriver

What the code could have been:

// Import the necessary modules
const { Client } = require('webdriverio');

// Define a function to get the client instance
async function getClient(browserType = 'chrome') {
  try {
    // Get the client instance
    const client = await Client.launch({
      capabilities: {
        browserName: browserType,
      },
    });
    return client;
  } catch (error) {
    console.error(`Failed to launch ${browserType} browser:`, error);
    process.exit(1); // Exit the process if client instance cannot be obtained
  }
}

// Define the main test function
async function testDriver() {
  try {
    // Get the client instance
    const driver = await getClient('chrome');

    // Define the test website URL
    const facebookUrl = 'https://www.facebook.com';

    // Navigate to the test website
    await driver.get(facebookUrl);

    // Wait for 4 seconds
    await new Promise((resolve) => setTimeout(resolve, 4000));
  } catch (error) {
    console.error('Test failed:', error);
  } finally {
    // Quit the browser in the end
    if (driver) {
      await driver.quit();
    }
  }
}

// Export the test function
module.exports = testDriver;

Code Breakdown

Import

Function

Function Body

Export