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.
npm run import -- "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
// 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
const getClient = importer.import('webdriver client')
importer
object.getClient
.async function testDriver()
testDriver
.let driver = await getClient()
getClient()
function and waits for its completion using the await
keyword.driver
.try {... } catch (e) {... } finally {... }
try
block contains the code that may throw an error.catch
block handles any errors thrown by the code in the try
block.finally
block is executed regardless of whether an error occurred.try
block:
let facebook = 'https://www.facebook.com'
facebook
.await driver.get(facebook)
get()
method on the driver
object, passing facebook
as an argument.await new Promise(resolve => setTimeout(resolve, 4000))
setTimeout()
function.await
keyword.catch
block:
console.log(e)
e
to the console.finally
block:
driver.quit()
quit()
method on the driver
object to close it.module.exports = testDriver
testDriver
function as a module.