The BaseDriver class is the foundational class that all Appium drivers extend from. It provides core functionality for session management, command execution, WebDriver protocol compliance, timeout handling, and element finding operations.
import { BaseDriver } from "appium-base-driver";import { BaseDriver, DeviceSettings } from "appium-base-driver";
class CustomDriver extends BaseDriver {
constructor(opts) {
super(opts);
// Set up device settings
this.settings = new DeviceSettings({
customSetting: 'defaultValue'
}, this.onSettingsUpdate.bind(this));
// Configure locator strategies
this.locatorStrategies = ['id', 'xpath', 'class name', 'accessibility id'];
this.webLocatorStrategies = ['css selector', 'link text'];
}
async onSettingsUpdate(key, newValue, oldValue) {
console.log(`Setting ${key} changed from ${oldValue} to ${newValue}`);
}
// Override session creation
async createSession(jwpDesiredCaps, jwpRequiredCaps, w3cCapabilities) {
const caps = await super.createSession(jwpDesiredCaps, jwpRequiredCaps, w3cCapabilities);
// Custom driver initialization
await this.initializeDevice();
return caps;
}
async initializeDevice() {
// Custom device initialization logic
}
}class BaseDriver extends Protocol {
constructor(opts = {}, shouldValidateCaps = true);
}Parameters:
opts (object, optional): Driver configuration options
tmpDir (string): Temporary directory path (defaults to system temp or APPIUM_TMP_DIR)port (number): Server port numbertimeout (number): Default timeout in millisecondsimplicitWait (number): Default implicit wait timeoutnewCommandTimeout (number): New command timeout (default: 60000ms)shouldValidateCaps (boolean, optional): Whether to validate capabilities (default: true)Key Properties:
sessionId - Current WebDriver session IDopts - Driver configuration optionscaps - Current session capabilitieshelpers - Helper functions objectsettings - DeviceSettings instancemanagedDrivers - Array of managed driver instancesasync createSession(jsonwpDesiredCapabilities, jsonwpRequiredCaps, w3cCapabilities);Creates a new WebDriver session with the provided capabilities.
Parameters:
jsonwpDesiredCapabilities (object): JSONWP desired capabilitiesjsonwpRequiredCaps (object): JSONWP required capabilitiesw3cCapabilities (object): W3C capabilities objectReturns: Promise<object> - Processed session capabilities
Example:
const caps = await driver.createSession(
{ platformName: 'iOS', deviceName: 'iPhone Simulator' },
{},
{
alwaysMatch: { platformName: 'iOS' },
firstMatch: [{ deviceName: 'iPhone Simulator' }]
}
);getSession();
getSessions();
sessionExists(sessionId);
async deleteSession(sessionId);getSession() - Returns current session capabilitiesgetSessions() - Returns array of active sessionssessionExists(sessionId) - Checks if session ID existsdeleteSession(sessionId) - Deletes specified sessionexecuteCommand(cmd, ...args);Main entry point for executing WebDriver commands with proper queueing, timeout handling, and error management.
Parameters:
cmd (string): Command name to execute...args (any[]): Command argumentsReturns: Promise<any> - Command result
Example:
// Execute find element command
const element = await driver.executeCommand('findElement', 'id', 'my-button');
// Execute click command
await driver.executeCommand('click', elementId);isMjsonwpProtocol();
isW3CProtocol();
setProtocolMJSONWP();
setProtocolW3C();
static determineProtocol(desiredCapabilities, requiredCapabilities, capabilities);isMjsonwpProtocol() - Returns true if using Mobile JSON Wire ProtocolisW3CProtocol() - Returns true if using W3C WebDriver protocolsetProtocolMJSONWP() - Sets protocol to MJSONWPsetProtocolW3C() - Sets protocol to W3CdetermineProtocol() - Static method to determine protocol from capabilitiesasync timeouts(timeoutsObj);
async getTimeouts();
async implicitWait(ms);
async newCommandTimeout(ms);
setImplicitWait(ms);
setNewCommandTimeout(ms);
clearNewCommandTimeout();
startNewCommandTimeout();
parseTimeoutArgument(ms);Examples:
// Set multiple timeouts (W3C format)
await driver.timeouts({
implicit: 5000,
pageLoad: 30000,
script: 10000
});
// Set implicit wait
await driver.implicitWait(5000);
// Set command timeout
await driver.newCommandTimeout(60000);async implicitWaitForCondition(condFn);Waits for a condition to become true using the implicit wait timeout.
Parameters:
condFn (function): Condition function that returns boolean or Promise<boolean>Example:
await driver.implicitWaitForCondition(async () => {
const elements = await driver.findElements('class name', 'loading');
return elements.length === 0;
});async findElement(strategy, selector);
async findElements(strategy, selector);
async findElementFromElement(strategy, selector, elementId);
async findElementsFromElement(strategy, selector, elementId);Parameters:
strategy (string): Locator strategy ('id', 'xpath', 'class name', etc.)selector (string): Element selectorelementId (string): Parent element ID (for findFrom methods)Returns:
findElement/findElementFromElement - Promise<string> - Element IDfindElements/findElementsFromElement - Promise<string[]> - Array of element IDsExamples:
// Find single element
const buttonId = await driver.findElement('id', 'submit-button');
// Find multiple elements
const textFields = await driver.findElements('class name', 'text-input');
// Find element within another element
const nestedElement = await driver.findElementFromElement('xpath', './/span', parentElementId);validateLocatorStrategy(strategy, webContext = false);Validates that a locator strategy is supported by the driver.
Parameters:
strategy (string): Locator strategy to validatewebContext (boolean): Whether in web context (uses webLocatorStrategies)validateDesiredCaps(caps);
logExtraCaps(caps);
get desiredCapConstraints();
set desiredCapConstraints(constraints);Example:
// Set capability constraints
driver.desiredCapConstraints = {
platformName: {
isString: true,
inclusionCaseInsensitive: ['iOS', 'Android']
},
deviceName: {
isString: true,
presence: true
}
};
// Validate capabilities
driver.validateDesiredCaps({
platformName: 'iOS',
deviceName: 'iPhone Simulator'
});logEvent(eventName);
get eventHistory();Records timing events for performance analysis and debugging.
Example:
// Log custom event
driver.logEvent('custom-operation-start');
// ... perform operation ...
driver.logEvent('custom-operation-end');
// Get event history
const history = driver.eventHistory;
console.log(history.commands); // Command execution historyproxyActive(sessionId);
getProxyAvoidList(sessionId);
canProxy(sessionId);Override these methods in subclasses to enable proxy functionality.
addManagedDriver(driver);
getManagedDrivers();Manage multiple driver instances for complex automation scenarios.
Example:
const webDriver = new WebDriver();
const mobileDriver = new MobileDriver();
driver.addManagedDriver(webDriver);
driver.addManagedDriver(mobileDriver);
const allDrivers = driver.getManagedDrivers();getStatus();
get driverData();
driverForSession(sessionId);
reset();getStatus() - Returns driver status informationdriverData - Returns driver-specific data for parallel sessionsdriverForSession() - Returns driver instance for specific sessionreset() - Resets session to original capabilitiesgetSwipeOptions(gestures, touchCount = 1);Processes swipe gesture parameters for touch actions.
Parameters:
gestures (array): Array of gesture objects with direction, startX, startY, etc.touchCount (number): Number of simultaneous touchesThe BaseDriver automatically handles errors and converts them to appropriate WebDriver protocol errors. Custom drivers can override error handling by catching exceptions and throwing appropriate protocol errors:
import { errors } from "appium-base-driver";
class CustomDriver extends BaseDriver {
async customMethod() {
try {
// Some operation that might fail
await riskyOperation();
} catch (err) {
throw new errors.UnknownError(`Custom operation failed: ${err.message}`);
}
}
}The BaseDriver supports extensive configuration through the constructor options and runtime properties:
newCommandTimeoutMs - Timeout for new commands (default: 60000ms)implicitWaitMs - Implicit wait timeout (default: 0ms)locatorStrategies - Array of supported locator strategieswebLocatorStrategies - Array of web-specific locator strategiesisCommandsQueueEnabled - Whether to queue commands for sequential execution (default: true)