Best JavaScript code snippet using appium-base-driver
errors.js
Source:errors.js
...607 }608 getActualError () {609 // If it's MJSONWP error, returns actual error cause for request failure based on `jsonwp.status`610 if (util.hasValue(this.jsonwp) && util.hasValue(this.jsonwp.status) && util.hasValue(this.jsonwp.value)) {611 return errorFromMJSONWPStatusCode(this.jsonwp.status, this.jsonwp.value);612 } else if (util.hasValue(this.w3c) && _.isNumber(this.w3cStatus) && this.w3cStatus >= 300) {613 return errorFromW3CJsonCode(this.w3c.error, this.w3c.message || this.message, this.w3c.stacktrace);614 }615 return new UnknownError(this.message);616 }617}618// map of error class name to error class619const errors = {NotYetImplementedError,620 NotImplementedError,621 BadParametersError,622 InvalidArgumentError,623 NoSuchDriverError,624 NoSuchElementError,625 UnknownCommandError,626 StaleElementReferenceError,627 ElementNotVisibleError,628 InvalidElementStateError,629 UnknownError,630 ElementIsNotSelectableError,631 ElementClickInterceptedError,632 ElementNotInteractableError,633 InsecureCertificateError,634 JavaScriptError,635 XPathLookupError,636 TimeoutError,637 NoSuchWindowError,638 NoSuchCookieError,639 InvalidCookieDomainError,640 InvalidCoordinatesError,641 UnableToSetCookieError,642 UnexpectedAlertOpenError,643 NoAlertOpenError,644 ScriptTimeoutError,645 InvalidElementCoordinatesError,646 IMENotAvailableError,647 IMEEngineActivationFailedError,648 InvalidSelectorError,649 SessionNotCreatedError,650 MoveTargetOutOfBoundsError,651 NoSuchAlertError,652 NoSuchContextError,653 InvalidContextError,654 NoSuchFrameError,655 UnableToCaptureScreen,656 UnknownMethodError,657 UnsupportedOperationError,658 ProxyRequestError};659// map of error code to error class660const jsonwpErrorCodeMap = {};661for (let ErrorClass of _.values(errors)) {662 if (ErrorClass.code) {663 jsonwpErrorCodeMap[ErrorClass.code()] = ErrorClass;664 }665}666const w3cErrorCodeMap = {};667for (let ErrorClass of _.values(errors)) {668 if (ErrorClass.error) {669 w3cErrorCodeMap[ErrorClass.error()] = ErrorClass;670 }671}672function isUnknownError (err) {673 return !err.constructor.name ||674 !_.values(errors).find(function equalNames (error) {675 return error.name === err.constructor.name;676 });677}678function isErrorType (err, type) {679 // `name` property is the constructor name680 if (type.name === ProtocolError.name) {681 // `jsonwpCode` is `0` on success682 return !!err.jsonwpCode;683 } else if (type.name === ProxyRequestError.name) {684 // `status` is `0` on success685 if (err.jsonwp) {686 return !!err.jsonwp.status;687 }688 if (_.isPlainObject(err.w3c)) {689 return _.isNumber(err.w3cStatus) && err.w3cStatus >= 300;690 }691 return false;692 }693 return err.constructor.name === type.name;694}695/**696 * Retrieve an error derived from MJSONWP status697 * @param {number} code JSONWP status code698 * @param {string|Object} value The error message, or an object with a `message` property699 * @return {ProtocolError} The error that is associated with provided JSONWP status code700 */701function errorFromMJSONWPStatusCode (code, value = '') {702 // if `value` is an object, pull message from it, otherwise use the plain703 // value, or default to an empty string, if null704 const message = (value || {}).message || value || '';705 if (code !== UnknownError.code() && jsonwpErrorCodeMap[code]) {706 mjsonwpLog.debug(`Matched JSONWP error code ${code} to ${jsonwpErrorCodeMap[code].name}`);707 return new jsonwpErrorCodeMap[code](message);708 }709 mjsonwpLog.debug(`Matched JSONWP error code ${code} to UnknownError`);710 return new UnknownError(message);711}712/**713 * Retrieve an error derived from W3C JSON Code714 * @param {string} code W3C error string (see https://www.w3.org/TR/webdriver/#handling-errors `JSON Error Code` column)715 * @param {string} message the error message716 * @param {?string} stacktrace an optional error stacktrace717 * @return {ProtocolError} The error that is associated with the W3C error string718 */719function errorFromW3CJsonCode (code, message, stacktrace = null) {720 if (code && w3cErrorCodeMap[code.toLowerCase()]) {721 w3cLog.debug(`Matched W3C error code '${code}' to ${w3cErrorCodeMap[code.toLowerCase()].name}`);722 const resultError = new w3cErrorCodeMap[code.toLowerCase()](message);723 resultError.stacktrace = stacktrace;724 return resultError;725 }726 w3cLog.debug(`Matched W3C error code '${code}' to UnknownError`);727 const resultError = new UnknownError(message);728 resultError.stacktrace = stacktrace;729 return resultError;730}731/**732 * Convert an Appium error to proper W3C HTTP response733 * @param {ProtocolError} err The error that needs to be translated734 */735function getResponseForW3CError (err) {736 let httpStatus;737 // W3C defined error message (https://www.w3.org/TR/webdriver/#dfn-error-code)738 let w3cErrorString;739 if (!err.w3cStatus) {740 err = util.hasValue(err.status)741 // If it's a JSONWP error, find corresponding error742 ? errorFromMJSONWPStatusCode(err.status, err.value)743 : new errors.UnknownError(err.message);744 }745 if (isErrorType(err, errors.BadParametersError)) {746 // respond with a 400 if we have bad parameters747 w3cLog.debug(`Bad parameters: ${err}`);748 w3cErrorString = BadParametersError.error();749 } else {750 w3cErrorString = err.error;751 }752 httpStatus = err.w3cStatus;753 if (!w3cErrorString) {754 w3cErrorString = UnknownError.error();755 }756 let httpResBody = {...
protocol.js
Source:protocol.js
...297 }298 // if the status is not 0, throw the appropriate error for status code.299 if (util.hasValue(driverRes)) {300 if (util.hasValue(driverRes.status) && !isNaN(driverRes.status) && parseInt(driverRes.status, 10) !== 0) {301 throw errorFromMJSONWPStatusCode(driverRes.status, driverRes.value);302 } else if (_.isPlainObject(driverRes.value) && driverRes.value.error) {303 throw errorFromW3CJsonCode(driverRes.value.error, driverRes.value.message, driverRes.value.stacktrace);304 }305 }306 httpResBody.value = driverRes;307 SESSIONS_CACHE.getLogger(req.params.sessionId || newSessionId, currentProtocol).debug(`Responding ` +308 `to client with driver.${spec.command}() result: ${_.truncate(JSON.stringify(driverRes), {length: MAX_LOG_BODY_LENGTH})}`);309 if (spec.command === DELETE_SESSION_COMMAND) {310 // We don't want to keep the logger instance in the cache311 // after the session is deleted, because it contains the logging history312 // and consumes the memory313 SESSIONS_CACHE.resetLogger(req.params.sessionId);314 }315 } catch (err) {...
errors-specs.js
Source:errors-specs.js
...251 for (let error of errorsList) {252 if (error.errorName !== 'NotYetImplementedError') {253 it(error.errorCode + ' should return correct error', function () {254 if (error.errorCode) {255 errorFromMJSONWPStatusCode(error.errorCode)256 .should.have.property('jsonwpCode', error.errorCode);257 errorFromMJSONWPStatusCode(error.errorCode)258 .should.have.property('message', error.errorMsg);259 if (!_.includes([13, 33], error.errorCode)) {260 errorFromMJSONWPStatusCode(error.errorCode, 'abcd')261 .should.have.property('jsonwpCode', error.errorCode);262 errorFromMJSONWPStatusCode(error.errorCode, 'abcd')263 .should.have.property('message', 'abcd');264 }265 } else {266 isErrorType(errorFromMJSONWPStatusCode(error.errorCode), errors.UnknownError).should.be.true;267 }268 });269 }270 }271 it('should throw unknown error for unknown code', function () {272 errorFromMJSONWPStatusCode(99)273 .should.have.property('jsonwpCode', 13);274 errorFromMJSONWPStatusCode(99)275 .should.have.property('message', 'An unknown server-side error occurred ' +276 'while processing the command.');277 });278});279describe('errorFromW3CJsonCode', function () {280 for (let error of errorsList) {281 if (error.errorName !== 'NotYetImplementedError') {282 it(error.errorName + ' should return correct error', function () {283 const {error: w3cError} = error;284 if (w3cError) {285 errorFromW3CJsonCode(w3cError).error.should.equal(error.error);286 errorFromW3CJsonCode(w3cError).should.have.property('message', error.errorMsg);287 } else {288 isErrorType(errorFromW3CJsonCode(w3cError), errors.UnknownError).should.be.true;...
proxy.js
Source:proxy.js
...259 let message = resBodyObj.value;260 if (_.has(message, 'message')) {261 message = message.message;262 }263 throw errorFromMJSONWPStatusCode(status, _.isEmpty(message) ? getSummaryByCode(status) : message);264 }265 } else if (protocol === W3C) {266 // Got response in W3C format267 if (response.statusCode < 300) {268 return resBodyObj.value;269 }270 if (_.isPlainObject(resBodyObj.value) && resBodyObj.value.error) {271 throw errorFromW3CJsonCode(resBodyObj.value.error, resBodyObj.value.message, resBodyObj.value.stacktrace);272 }273 } else if (response.statusCode === 200) {274 // Unknown protocol. Keeping it because of the backward compatibility275 return resBodyObj;276 }277 throw new errors.UnknownError(`Did not know what to do with response code '${response.statusCode}' ` +...
utils.js
Source:utils.js
...195 throw new Error(`Result has unexpected type: (${typeof res}).`);196 }197 if (res.status && res.status !== 0) {198 // we got some form of error.199 throw errorFromMJSONWPStatusCode(res.status, res.value.message || res.value);200 }201 // with either have an object with a `value` property (even if `null`),202 // or a plain object203 const value = _.has(res, 'value') ? res.value : res;204 // get rid of noisy functions on objects205 if (_.isObject(value)) {206 for (const property of ['ceil', 'clone', 'floor', 'round', 'scale', 'toString']) {207 delete value[property];208 }209 }210 return value;211}212export {213 appInfoFromDict, pageArrayFromDict, getDebuggerAppKey,...
index.js
Source:index.js
1// transpile:main2// BaseDriver exports3import * as driver from './lib/basedriver/driver';4import * as image from './lib/basedriver/image-element';5import * as deviceSettings from './lib/basedriver/device-settings';6const { BaseDriver } = driver;7const { ImageElement } = image;8const { DeviceSettings, BASEDRIVER_HANDLED_SETTINGS } = deviceSettings;9export { BaseDriver, DeviceSettings, ImageElement, BASEDRIVER_HANDLED_SETTINGS };10export default BaseDriver;11// MJSONWP exports12import * as protocol from './lib/protocol';13const {14 Protocol, routeConfiguringFunction, errors, isErrorType,15 errorFromMJSONWPStatusCode, errorFromW3CJsonCode, ALL_COMMANDS, METHOD_MAP,16 routeToCommandName, NO_SESSION_ID_COMMANDS, isSessionCommand,17} = protocol;18export {19 Protocol, routeConfiguringFunction, errors, isErrorType,20 errorFromMJSONWPStatusCode, errorFromW3CJsonCode,21 errorFromMJSONWPStatusCode as errorFromCode, ALL_COMMANDS, METHOD_MAP,22 routeToCommandName, NO_SESSION_ID_COMMANDS, isSessionCommand };23// Express exports24import * as staticIndex from './lib/express/static';25const { STATIC_DIR } = staticIndex;26export { STATIC_DIR };27import * as serverIndex from './lib/express/server';28const { server } = serverIndex;29export { server };30// jsonwp-proxy exports31import * as proxyIndex from './lib/jsonwp-proxy/proxy';32const { JWProxy } = proxyIndex;33export { JWProxy };34// jsonwp-status exports35import * as statusIndex from './lib/jsonwp-status/status';36const { codes: statusCodes, getSummaryByCode } = statusIndex;37export { statusCodes, getSummaryByCode };38// W3C capabilities parser39import * as caps from './lib/basedriver/capabilities';40const { processCapabilities, isStandardCap } = caps;41export { processCapabilities, isStandardCap };42// Web socket helpers43import * as ws from './lib/express/websocket';44const { DEFAULT_WS_PATHNAME_PREFIX } = ws;...
Using AI Code Generation
1var BaseDriver = require('appium-base-driver');2var errorFromMJSONWPStatusCode = BaseDriver.errorFromMJSONWPStatusCode;3var errorFromW3CJsonCode = BaseDriver.errorFromW3CJsonCode;4var errorFromCode = BaseDriver.errorFromCode;5var MJSONWP = BaseDriver.MJSONWP;6var W3C = BaseDriver.W3C;7var APP = BaseDriver.APP;8var JSONWP = BaseDriver.JSONWP;9var BASE = BaseDriver.BASE;10var SELENIUM = BaseDriver.SELENIUM;11var HTTP = BaseDriver.HTTP;12var WD = BaseDriver.WD;13var IOS = BaseDriver.IOS;14console.log('Error from MJSONWP Status Code: ', errorFromMJSONWPStatusCode(6));15console.log('Error from W3C Json Code: ', errorFromW3CJsonCode(6));16console.log('Error from Code: ', errorFromCode(6));17console.log('MJSONWP Error Codes: ', MJSONWP);18console.log('W3C Error Codes: ', W3C);19console.log('Appium Error Codes: ', APP);20console.log('JSONWP Error Codes: ', JSONWP);21console.log('BaseDriver Error Codes: ', BASE);22console.log('Selenium Error Codes: ', SELENIUM);23console.log('HTTP Error Codes: ', HTTP);24console.log('WebDriver Error Codes: ', WD);25console.log('IOS Error Codes: ', IOS);
Using AI Code Generation
1const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;2const { errors } = require('appium-base-driver');3const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;4const { errors } = require('appium-base-driver');5const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;6const { errors } = require('appium-base-driver');7const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;8const { errors } = require('appium-base-driver');9const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;10const { errors } = require('appium-base-driver');11const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;12const { errors } = require('appium-base-driver');13const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;14const { errors } = require('appium-base-driver');15const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;16const { errors } = require('appium-base-driver');17const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;18const { errors } = require('appium-base-driver');19const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors;20const { errors } = require('appium-base-driver');21const { errorFromMJSONWPStatusCode } = require('appium-base-driver').errors
Using AI Code Generation
1const {errorFromMJSONWPStatusCode} = require('./lib/basedriver/driver');2const err = errorFromMJSONWPStatusCode(13);3console.log(err);4const {errorFromW3CJsonCode} = require('./lib/basedriver/driver');5const err = errorFromW3CJsonCode(13);6console.log(err);7[HTTP] {"capabilities":{"alwaysMatch":{"platformName":"Android","appium:deviceName":"Android Emulator","appium:platformVersion":"7.1.1","appium:app":"/Users/MyUser/Downloads/ApiDemos-debug.apk","appium:automationName":"UiAutomator2"},"firstMatch":[{}]},"desiredCapabilities":{"platformName":"Android","deviceName":"Android Emulator","platformVersion":"7.1.1","app":"/Users/MyUser/Downloads/ApiDemos-debug.apk","automationName":"UiAutomator2"}}8[MJSONWP] Calling AppiumDriver.createSession() with args: [{"platformName":"Android","deviceName":"Android Emulator","platformVersion":"7.1.1","app":"/Users/MyUser/Downloads/ApiDemos-debug.apk","automationName":"UiAutomator2"},null,{"alwaysMatch":{"platformName":"Android","appium:deviceName":"Android Emulator","appium:platformVersion":"7.1.1","appium:app":"/Users/MyUser/Downloads/ApiDemos-debug.apk","appium:automationName":"UiAutomator2"},"firstMatch":[{}]}]9[BaseDriver] Event 'newSessionRequested' logged at 1549386450813 (13:40:50 GMT+0530 (IST))10[Appium] Appium v1.11.0 creating new AndroidUiautomator2Driver (v1.26.0) session
Using AI Code Generation
1const { errorFromMJSONWPStatusCode } = require('appium-base-driver');2let error = errorFromMJSONWPStatusCode(6, 'message');3console.log(error);4{ Error: message5 at Object.errorFromMJSONWPStatusCode (/Users/krishna/Desktop/Projects/appium/node_modules/appium-base-driver/lib/mjsonwp/errors.js:124:11)6 at Object. (/Users/krishna/Desktop/Projects/appium/test.js:3:23)7 at Module._compile (internal/modules/cjs/loader.js:778:30)8 at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)9 at Module.load (internal/modules/cjs/loader.js:653:32)10 at tryModuleLoad (internal/modules/cjs/loader.js:593:12)11 at Function.Module._load (internal/modules/cjs/loader.js:585:3)12 at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)13 at startup (internal/bootstrap/node.js:283:19)14 at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)15 httpStatus: 500 }
Using AI Code Generation
1const { errorFromMJSONWPStatusCode, errors } = require('appium-base-driver');2console.log(errorFromMJSONWPStatusCode(errors.NoSuchElement.code, 'test error message'));3const { errorFromW3CJsonCode, errors: w3cErrors } = require('appium-base-driver');4console.log(errorFromW3CJsonCode(w3cErrors.NoSuchElement.code, 'test error message'));5const { errorFromCode, errors: newErrors } = require('appium-base-driver');6console.log(errorFromCode(newErrors.NoSuchElement.code, 'test error message'));7const { AppiumError } = require('appium-base-driver');8console.log(new AppiumError('test error message'));9 at Object.errorFromMJSONWPStatusCode (/Users/username/Desktop/appium-base-driver/test.js:5:13)10 at Object.<anonymous> (/Users/username/Desktop/appium-base-driver/test.js:19:21)11 at Module._compile (internal/modules/cjs/loader.js:999:30)12 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)13 at Module.load (internal/modules/cjs/loader.js:863:32)14 at Function.Module._load (internal/modules/cjs/loader.js:708:14)15 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)16 jsonwp: { status: 7, value: [Object] },17 cause: null }18 at Object.errorFromW3CJsonCode (/Users/username/Desktop/appium-base-driver/test.js:9:13)19 at Object.<anonymous> (/Users/username/Desktop/appium-base-driver/test.js:20:21)20 at Module._compile (internal/modules/cjs/loader.js:999:30)21 at Object.Module._extensions..js (internal/modules/cjs
Using AI Code Generation
1const {errorFromMJSONWPStatusCode} = require('appium-base-driver').errors;2let error = errorFromMJSONWPStatusCode(13, 'Custom error message');3console.log(error);4 at Object.errorFromMJSONWPStatusCode (/Users/isaacmurchie/Downloads/appium/node_modules/appium-base-driver/lib/protocol/errors.js:47:11)5 at Object. (/Users/isaacmurchie/Downloads/appium/test.js:4:26)6 at Module._compile (internal/modules/cjs/loader.js:1137:30)7 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)8 at Module.load (internal/modules/cjs/loader.js:985:32)9 at Function.Module._load (internal/modules/cjs/loader.js:878:14)10 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!