Appium Base Driver provides the foundational base driver class and utilities that all Appium drivers inherit from, serving as the core infrastructure for the Appium mobile automation framework. It includes session management, WebDriver protocol support, HTTP server functionality, command proxy capabilities, and comprehensive error handling.
npm install appium-base-driverimport { BaseDriver, DeviceSettings } from "appium-base-driver";For individual components:
import {
BaseDriver,
DeviceSettings,
Protocol,
errors,
JWProxy,
server,
statusCodes,
processCapabilities,
STATIC_DIR,
DEFAULT_WS_PATHNAME_PREFIX,
routeConfiguringFunction,
getSummaryByCode,
ALL_COMMANDS,
METHOD_MAP,
routeToCommandName,
NO_SESSION_ID_COMMANDS,
isSessionCommand,
isErrorType,
errorFromMJSONWPStatusCode,
errorFromCode, // alias for errorFromMJSONWPStatusCode
errorFromW3CJsonCode
} from "appium-base-driver";CommonJS:
const { BaseDriver, DeviceSettings } = require("appium-base-driver");import { BaseDriver, DeviceSettings } from "appium-base-driver";
// Create a custom driver by extending BaseDriver
class MyDriver extends BaseDriver {
constructor(opts) {
super(opts);
// Configure device settings
this.settings = new DeviceSettings({
defaultTimeout: 30000,
implicitWait: 5000
});
}
// Implement required methods
async createSession(jwpDesiredCaps, jwpRequiredCaps, w3cCapabilities) {
// Session creation logic
const caps = await super.createSession(jwpDesiredCaps, jwpRequiredCaps, w3cCapabilities);
// Custom initialization
return caps;
}
// Override find element behavior
async findElement(strategy, selector) {
if (strategy === 'custom-strategy') {
// Custom element finding logic
return this.customFindElement(selector);
}
return await super.findElement(strategy, selector);
}
}
// Create driver instance
const driver = new MyDriver({
port: 4723,
timeout: 60000
});Appium Base Driver is built around several key components:
The foundational BaseDriver class that all Appium drivers extend from, providing session management, command execution, protocol handling, and timeout management.
class BaseDriver extends Protocol {
constructor(opts = {}, shouldValidateCaps = true);
// Session management
async createSession(jsonwpDesiredCapabilities, jsonwpRequiredCaps, w3cCapabilities);
async deleteSession(sessionId);
getSession();
getSessions();
sessionExists(sessionId);
// Command execution
executeCommand(cmd, ...args);
// Protocol methods
isMjsonwpProtocol();
isW3CProtocol();
setProtocolMJSONWP();
setProtocolW3C();
}Complete WebDriver and Mobile JSON Wire Protocol implementation with comprehensive error classes, route mapping, and status code handling.
// Error handling
const errors = {
ProtocolError: class ProtocolError extends Error,
NoSuchElementError: class NoSuchElementError extends ProtocolError,
TimeoutError: class TimeoutError extends ProtocolError,
// ... all WebDriver error classes
};
function isErrorType(err, type);
function errorFromMJSONWPStatusCode(code, message);
function errorFromW3CJsonCode(code, message, stacktrace);
// Route configuration
function routeConfiguringFunction(driver);
const ALL_COMMANDS = [...]; // Array of all supported commands
const METHOD_MAP = {...}; // HTTP route to command mappingHTTP server functionality with WebDriver route configuration, static asset serving, and WebSocket support.
function server(configureRoutes, port, hostname);
// Static assets
const STATIC_DIR; // Path to static directory
// WebSocket support
const DEFAULT_WS_PATHNAME_PREFIX = '/ws';Proxy functionality for forwarding WebDriver commands to other servers, enabling driver composition and command delegation.
class JWProxy {
constructor(opts = {});
// Core proxy methods
proxy(url, method, body);
command(url, method, body);
proxyReqRes(req, res);
// Request management
getActiveRequestsCount();
cancelActiveRequests();
}Dynamic configuration management system with validation, update callbacks, and runtime setting modifications.
class DeviceSettings {
constructor(defaultSettings = {}, onSettingsUpdate = null);
update(newSettings);
getSettings();
}W3C WebDriver capabilities processing and validation system for handling both legacy JSONWP and modern W3C capability formats.
function processCapabilities(caps, constraints, shouldValidateCaps);WebDriver status codes, constants, and utility functions for protocol compliance and error handling.
const statusCodes = {
Success: { code: 0, summary: 'The command executed successfully.' },
NoSuchDriver: { code: 6, summary: 'A session is either terminated or not started' },
NoSuchElement: { code: 7, summary: 'An element could not be located on the page using the given search parameters.' },
NoSuchFrame: { code: 8, summary: 'A request to switch to a frame could not be satisfied because the frame could not be found.' },
UnknownCommand: { code: 9, summary: 'The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource.' },
StaleElementReference: { code: 10, summary: 'An element command failed because the referenced element is no longer attached to the DOM.' },
ElementNotVisible: { code: 11, summary: 'An element command could not be completed because the element is not visible on the page.' },
InvalidElementState: { code: 12, summary: 'An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element).' },
UnknownError: { code: 13, summary: 'An unknown server-side error occurred while processing the command.' },
ElementIsNotSelectable: { code: 15, summary: 'An attempt was made to select an element that cannot be selected.' },
JavaScriptError: { code: 17, summary: 'An error occurred while executing user supplied JavaScript.' },
XPathLookupError: { code: 19, summary: 'An error occurred while searching for an element by XPath.' },
Timeout: { code: 21, summary: 'An operation did not complete before its timeout expired.' },
NoSuchWindow: { code: 23, summary: 'A request to switch to a different window could not be satisfied because the window could not be found.' },
InvalidCookieDomain: { code: 24, summary: 'An illegal attempt was made to set a cookie under a different domain than the current page.' },
UnableToSetCookie: { code: 25, summary: 'A request to set a cookie\'s value could not be satisfied.' },
UnexpectedAlertOpen: { code: 26, summary: 'A modal dialog was open, blocking this operation' },
NoAlertOpenError: { code: 27, summary: 'An attempt was made to operate on a modal dialog when one was not open.' },
ScriptTimeout: { code: 28, summary: 'A script did not complete before its timeout expired.' },
InvalidElementCoordinates: { code: 29, summary: 'The coordinates provided to an interactions operation are invalid.' },
IMENotAvailable: { code: 30, summary: 'IME was not available.' },
IMEEngineActivationFailed: { code: 31, summary: 'An IME engine could not be started.' },
InvalidSelector: { code: 32, summary: 'Argument was an invalid selector (e.g. XPath/CSS).' },
SessionNotCreatedException: { code: 33, summary: 'A new session could not be created.' },
MoveTargetOutOfBounds: { code: 34, summary: 'Target provided for a move action is out of bounds.' },
NoSuchContext: { code: 35, summary: 'No such context found.' }
};
function getSummaryByCode(code);// Base driver configuration
interface DriverOpts {
port?: number;
timeout?: number;
tmpDir?: string;
implicitWait?: number;
newCommandTimeout?: number;
}
// Session capabilities
interface Capabilities {
platformName?: string;
deviceName?: string;
app?: string;
browserName?: string;
version?: string;
// ... W3C and JSONWP capabilities
}
// Command execution context
interface CommandContext {
sessionId?: string;
elementId?: string;
parameters?: any;
}
// WebDriver protocol types
type Protocol = 'W3C' | 'MJSONWP';
// Locator strategies
type LocatorStrategy = 'id' | 'xpath' | 'name' | 'class name' | 'tag name' |
'link text' | 'partial link text' | 'css selector' |
'accessibility id' | string;
// Proxy configuration
interface ProxyOpts {
scheme?: string;
server?: string;
port?: number;
base?: string;
timeout?: number;
}
// Validation result
interface ValidationResult {
isValid: boolean;
errors?: string[];
}
// Event history
interface EventHistory {
commands: CommandEvent[];
[eventName: string]: any[];
}
interface CommandEvent {
cmd: string;
startTime: number;
endTime?: number;
}
// Settings configuration
interface SettingsObject {
[key: string]: any;
}
// WebSocket handler configuration
interface WebSocketHandler {
pathname: string;
server: any; // WebSocket server instance
}
// Element finding result
interface Element {
id: string;
[key: string]: any;
}
// HTTP request/response types
interface Request {
method: string;
url: string;
headers: { [key: string]: string };
body?: any;
params?: { [key: string]: string };
query?: { [key: string]: string };
}
interface Response {
status(code: number): Response;
json(data: any): void;
send(data: any): void;
header(name: string, value: string): Response;
cookie(name: string, value: string, options?: any): Response;
}
// Status code entry
interface StatusCodeEntry {
code: number;
summary: string;
}
// Route configuration
type RouteConfigFunction = (app: any) => void;
// Command mapping
interface CommandMapping {
[route: string]: {
command: string;
payloadParams?: any;
};
}