Best JavaScript code snippet using appium-base-driver
errors-specs.js
Source:errors-specs.js
...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;289 }290 });291 }292 }293 it('should parse unknown errors', function () {294 isErrorType(errorFromW3CJsonCode('not a real error code'), errors.UnknownError).should.be.true;295 errorFromW3CJsonCode('not a real error code').message.should.match(/An unknown server-side error occurred/);296 errorFromW3CJsonCode('not a real error code').error.should.equal('unknown error');297 });298});299describe('w3c Status Codes', function () {300 it('should match the correct error codes', function () {301 let non400Errors = [302 ['NoSuchDriverError', 404],303 ['NoSuchFrameError', 404],304 ['NoAlertOpenError', 404],305 ['NoSuchWindowError', 404],306 ['StaleElementReferenceError', 404],307 ['JavaScriptError', 500],308 ['MoveTargetOutOfBoundsError', 500],309 ['NoSuchCookieError', 404],310 ['NoSuchElementError', 404],311 ['ScriptTimeoutError', 408],312 ['SessionNotCreatedError', 500],313 ['TimeoutError', 408],314 ['UnableToSetCookieError', 500],315 ['UnableToCaptureScreen', 500],316 ['UnexpectedAlertOpenError', 500],317 ['UnknownCommandError', 404],318 ['UnknownError', 500],319 ['UnknownMethodError', 405],320 ['UnsupportedOperationError', 500],321 ];322 // Test the errors that we don't expect to return 400 code323 for (let [errorName, expectedErrorCode] of non400Errors) {324 errors[errorName].should.exist;325 (new errors[errorName]()).should.have.property('w3cStatus', expectedErrorCode);326 }327 // Test an error that we expect to return 400 code328 (new errors.ElementClickInterceptedError()).should.have.property('w3cStatus', 400);329 });330});331describe('.getResponseForW3CError', function () {332 it('should return an error, message and stacktrace for just a generic exception', function () {333 try {334 throw new Error('Some random error');335 } catch (e) {336 const [httpStatus, httpResponseBody] = getResponseForW3CError(e);337 httpStatus.should.equal(500);338 const {error, message, stacktrace} = httpResponseBody.value;339 message.should.match(/Some random error/);340 error.should.equal('unknown error');341 stacktrace.should.match(/at getResponseForW3CError/);342 stacktrace.should.match(/Some random error/);343 stacktrace.should.match(/errors-specs.js/);344 }345 });346 it('should return an error, message and stacktrace for a NoSuchElementError', function () {347 const noSuchElementError = new errors.NoSuchElementError('specific error message');348 const [httpStatus, httpResponseBody] = getResponseForW3CError(noSuchElementError);349 httpStatus.should.equal(404);350 const {error, message, stacktrace} = httpResponseBody.value;351 error.should.equal('no such element');352 message.should.match(/specific error message/);353 stacktrace.should.match(/errors-specs.js/);354 });355 it('should handle BadParametersError', function () {356 const badParamsError = new errors.BadParametersError('__FOO__', '__BAR__', '__HELLO_WORLD__');357 const [httpStatus, httpResponseBody] = getResponseForW3CError(badParamsError);358 httpStatus.should.equal(400);359 const {error, message, stacktrace} = httpResponseBody.value;360 error.should.equal('invalid argument');361 message.should.match(/__BAR__/);362 message.should.match(/__HELLO_WORLD__/);363 stacktrace.should.match(/errors-specs.js/);364 });365 it('should translate JSONWP errors', function () {366 const [httpStatus, httpResponseBody] = getResponseForW3CError({367 status: 7,368 value: 'My custom message',369 sessionId: 'Fake Session Id',370 });371 httpStatus.should.equal(404);372 const {error, message, stacktrace} = httpResponseBody.value;373 message.should.equal('My custom message');374 error.should.equal('no such element');375 stacktrace.should.exist;376 });377});378describe('.getActualError', function () {379 describe('MJSONWP', function () {380 it('should map a status code 7 no such element error as a NoSuchElementError', function () {381 const actualError = new errors.ProxyRequestError('Error message does not matter', {382 value: 'does not matter',383 status: 7,384 }).getActualError();385 isErrorType(actualError, errors.NoSuchElementError).should.be.true;386 });387 it('should map a status code 10, StaleElementReferenceError', function () {388 const actualError = new errors.ProxyRequestError('Error message does not matter', {389 value: 'Does not matter',390 status: 10,391 }).getActualError();392 isErrorType(actualError, errors.StaleElementReferenceError).should.be.true;393 });394 it('should map an unknown error to UnknownError', function () {395 const actualError = new errors.ProxyRequestError('Error message does not matter', {396 value: 'Does not matter',397 status: -100398 }).getActualError();399 isErrorType(actualError, errors.UnknownError).should.be.true;400 });401 it('should parse a JSON string', function () {402 const actualError = new errors.ProxyRequestError('Error message does not matter', JSON.stringify({403 value: 'Does not matter',404 status: -100405 })).getActualError();406 isErrorType(actualError, errors.UnknownError).should.be.true;407 });408 });409 describe('W3C', function () {410 it('should map a 404 no such element error as a NoSuchElementError', function () {411 const actualError = new errors.ProxyRequestError('Error message does not matter', {412 value: {413 error: errors.NoSuchElementError.error(),414 },415 }, HTTPStatusCodes.NOT_FOUND).getActualError();416 isErrorType(actualError, errors.NoSuchElementError).should.be.true;417 });418 it('should map a 400 StaleElementReferenceError', function () {419 const actualError = new errors.ProxyRequestError('Error message does not matter', {420 value: {421 error: errors.StaleElementReferenceError.error(),422 },423 }, HTTPStatusCodes.BAD_REQUEST).getActualError();424 isErrorType(actualError, errors.StaleElementReferenceError).should.be.true;425 });426 it('should map an unknown error to UnknownError', function () {427 const actualError = new errors.ProxyRequestError('Error message does not matter', null, {428 value: {429 error: 'Not a valid w3c JSON code'430 },431 }, 456).getActualError();432 isErrorType(actualError, errors.UnknownError).should.be.true;433 });434 it('should parse a JSON string', function () {435 const actualError = new errors.ProxyRequestError('Error message does not matter', JSON.stringify({436 value: {437 error: errors.StaleElementReferenceError.error(),438 },439 }), HTTPStatusCodes.BAD_REQUEST).getActualError();440 isErrorType(actualError, errors.StaleElementReferenceError).should.be.true;441 });442 });...
eaiError.js
Source:eaiError.js
...120 _.set(simpleObject, CAUSE, toPrintableError(_.get(error, CAUSE)));121 }122 return simpleObject;123}124function isErrorType(error, type) {125 if (!(error instanceof EaiError)) {126 return false;127 }128 return _.get(error, TYPE) === type;129}130function isConflict(error) {131 return isErrorType(error, CONFLICT);132}133function isNotFound(error) {134 return isErrorType(error, NOT_FOUND);135}136function isIllegalArguments(error) {137 return isErrorType(error, BAD_REQUEST);138}139function isServiceUnavailable(error) {140 return isErrorType(error, SERVICE_UNAVAILABLE);141}142function isDbError(error) {143 return error instanceof EaiError && _.get(error, [DETAILS, DB_ERROR]);144}145function isNoContent(error) {146 return isErrorType(error, NO_CONTENT);147}148function createError(message, type, details, cause) {149 return new EaiError(150 message,151 {152 [CAUSE]: cause,153 [TYPE]: type,154 [DETAILS]: details155 },156 createError157 );158}159function createSqlAndCodeOutOfSyncError(details) {160 return createError(SQL_AND_CODE_OUT_OF_SYNC_MSG, INTERNAL_SERVER_ERROR, details);...
errors.test.js
Source:errors.test.js
...17 });18 });19 describe('isErrorType', () => {20 it('returns false if not an error', () => {21 expect(isErrorType()).toBe(false);22 expect(isErrorType(false, ERROR.BAD_COLLECTIVE_TYPE)).toBe(false);23 expect(isErrorType(null, ERROR.BAD_COLLECTIVE_TYPE)).toBe(false);24 expect(isErrorType('', ERROR.BAD_COLLECTIVE_TYPE)).toBe(false);25 expect(isErrorType(new Error(), ERROR.BAD_COLLECTIVE_TYPE)).toBe(false);26 expect(isErrorType(new Error())).toBe(false);27 });28 it('returns whether error is the same type or not', () => {29 const error = createError(ERROR.BAD_COLLECTIVE_TYPE);30 expect(isErrorType(error, ERROR.BAD_COLLECTIVE_TYPE)).toBe(true);31 expect(isErrorType(error, ERROR.FORM_FIELD_MAX)).toBe(false);32 });33 });34 describe('getErrorFromGraphqlException', () => {35 it('returns an unknown error if no data is available', () => {36 expect(getErrorFromGraphqlException().type).toBe(ERROR.UNKNOWN);37 expect(getErrorFromGraphqlException({ graphQLErrors: [] }).type).toBe(ERROR.UNKNOWN);38 expect(getErrorFromGraphqlException({ networkError: { result: { errors: [] } } }).type).toBe(ERROR.UNKNOWN);39 });40 it('returns a proper error from extensions.code', () => {41 expect(42 getErrorFromGraphqlException({ graphQLErrors: [{ extensions: { code: ERROR.BAD_COLLECTIVE_TYPE } }] }).type,43 ).toBe(ERROR.BAD_COLLECTIVE_TYPE);44 });45 it('retrieves the message from the first error (known or unknown)', () => {...
find.js
Source:find.js
...30 element = await this.doFindElementOrEls(params);31 } catch (err) {32 // if the error that comes back is from a proxied request, we need to33 // unwrap it to its actual protocol error first34 if (isErrorType(err, errors.ProxyRequestError)) {35 err = err.getActualError(); // eslint-disable-line no-ex-assign36 }37 // now we have to inspect the error to determine if it is a no such38 // element error, based on the shape of the error object from39 // @appium/base-driver40 if (isErrorType(err, errors.NoSuchElementError)) {41 // we are fine with this, just indicate a retry42 return false;43 }44 throw err;45 }46 // we want to return false if we want to potentially try again47 return !_.isEmpty(element);48 };49 try {50 await this.implicitWaitForCondition(doFind);51 } catch (err) {52 if (err.message && err.message.match(/Condition unmet/)) {53 // only get here if we are looking for multiple elements54 // condition was not met setting res to empty array...
fetch.js
Source:fetch.js
1import axios from 'axios'2import { showLoading, hideLoading } from '../load/loading'3import { Message } from 'element-ui'4import {5 Cookie,6 Key7} from '../cache/cookie'8import { contentType, needLoadingRequest, requestTimeout, CANCEL_REQUEST_TYPE } from '~/config/website'9const service = axios.create({10 baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url11 timeout: requestTimeout,12 headers: {13 'Content-Type': contentType14 }15})16service.interceptors.request.use(params => {17 const config = {18 ...params19 }20 config.headers.Authorization = `Bearer ${Cookie.get(Key.accessTokenKey).replace(/"/g, '')}`21 const needLoading = () => {22 let status = true23 needLoadingRequest.some(item => {24 if (item !== config.url) {25 status = false26 }27 })28 return status29 }30 if (needLoading()) {31 showLoading()32 }33 // console.log(config);34 return config35}, error => {36 return Promise.reject(error)37})38service.interceptors.response.use(response => {39 hideLoading()40 const res = response.data41 if (res.code !== 20000) {42 Message({43 message: res.message || 'Error',44 type: 'error',45 duration: 5 * 100046 })47 return Promise.reject(res.message || 'Error')48 }49 return res50},51error => {52 // å¦ææ¯åæ¶è¯·æ±ç±»åå忽ç¥å¼å¸¸å¤ç53 hideLoading()54 let isErrorType55 try {56 const errorType = (JSON.parse(error.message) || {}).type57 isErrorType = errorType === CANCEL_REQUEST_TYPE58 } catch (error) {59 isErrorType = false60 }61 const response = error.response62 if (!isErrorType) {63 // eslint-disable-next-line64 if (response.status === 401 && response.data.code === 1401) {65 let isLock = true66 if (isLock && Cookie.get(Key.refreshTokenKey)) {67 // æå·æ°ä»¤ç68 isLock = false69 window.location.href = `${process.env.VUE_APP_AUTH_URL}/refresh?redirectURL=${window.location.href}`70 } else {71 window.location.href = `${process.env.VUE_APP_AUTH_URL}?redirectURL=${window.location.href}`72 }73 return Promise.reject(response.data.message || 'Error')74 }75 Message({76 message: response.data.message || 'Error',77 type: 'error',78 duration: 5 * 100079 })80 return Promise.reject(response.data.message || 'Error')81 }82})...
exec.js
Source:exec.js
1const execa = require('execa');2const logger = require('./logger');3const loggerLabel = 'exec';4class OutputPipe {5 constructor(bufferSize, log, loggerLabel) {6 this.output = '';7 this.content = [];8 this.bufferSize = bufferSize || 100;9 this.logOutput = (log !== false);10 this.loggerLabel = loggerLabel;11 }12 log(str, isErrorType) {13 let reminder = '';14 str.split('\n').forEach((v, i, splits) => {15 if (i < splits.length - 1) {16 v && (this.logOutput || isErrorType) && logger.debug({label: this.loggerLabel, message: v});17 if (this.content.length > this.bufferSize) {18 this.content.shift();19 }20 this.content.push(v);21 } else {22 reminder = v;23 }24 });25 return reminder;26 }27 push(str, isErrorType) {28 if (str) {29 this.output = this.log(this.output + str, isErrorType) || '';30 }31 }32 flush() {33 this.log(this.output + '\n');34 }35}36module.exports = {37 'exec': (cmd, args, options) => {38 //logger.debug({label: loggerLabel, message: 'executing: ' + cmd + ' ' + (args && args.join(' '))});39 const outputPipe = new OutputPipe(100, options && options.log, cmd.substr(cmd.lastIndexOf('/') + 1));40 const spawn = execa(cmd, args, options);41 spawn.stdout.on('data', (data) => {42 outputPipe.push(String.fromCharCode.apply(null, new Uint16Array(data)));43 });44 spawn.stderr.on('data', (data) => {45 outputPipe.push(String.fromCharCode.apply(null, new Uint16Array(data)), true);46 });47 return new Promise((resolve, reject) => {48 spawn.on('close', code => {49 outputPipe.flush();50 if (code == 0) {51 resolve(outputPipe.content);52 } else {53 reject(code);54 }55 });56 });57 }...
errorSerializer.js
Source:errorSerializer.js
...23 message,24 stack25})26export const serialize = err => Promise.reject(isError(err) ? toErrorInfo(err) : err)27export const deserialize = err => isErrorType(err) ? toError(err) : err28// WEBPACK FOOTER //...
index.js
Source:index.js
1// transpile:main2import {3 Protocol, isSessionCommand, routeConfiguringFunction, determineProtocol4} from './protocol';5import {6 NO_SESSION_ID_COMMANDS, ALL_COMMANDS, METHOD_MAP,7 routeToCommandName8} from './routes';9import {10 errors, isErrorType, errorFromMJSONWPStatusCode, errorFromW3CJsonCode11} from './errors';12export {13 Protocol, routeConfiguringFunction, errors, isErrorType,14 errorFromMJSONWPStatusCode, errorFromW3CJsonCode, ALL_COMMANDS, METHOD_MAP,15 routeToCommandName, NO_SESSION_ID_COMMANDS, isSessionCommand, determineProtocol,...
Using AI Code Generation
1const BaseDriver = require('appium-base-driver');2const { isErrorType } = require('appium-base-driver').errors;3const BaseDriver = require('appium-base-driver');4const { isErrorType } = require('appium-base-driver').errors;5let driver = new BaseDriver();6let error = new Error('This is a sample error');7if (isErrorType(error, BaseDriver.errors.NotYetImplementedError)) {8 console.log('Error is of type NotYetImplementedError');9} else {10 console.log('Error is not of type NotYetImplementedError');11}12if (isErrorType(error, BaseDriver.errors.NotYetImplementedError)) {13 console.log('Error is of type NotYetImplementedError');14} else {15 console.log('Error is not of type NotYetImplementedError');16}17const BaseDriver = require('appium-base-driver');18const { isErrorType } = require('appium-base-driver').errors;19const BaseDriver = require('appium-base-driver');20const { isErrorType } = require('appium-base-driver').errors;21let driver = new BaseDriver();22let error = new Error('This is a sample error');23if (isErrorType(error, BaseDriver.errors.NotYetImplementedError)) {24 console.log('Error is of type NotYetImplementedError');25} else {26 console.log('Error is not of type NotYetImplementedError');27}28if (isErrorType(error, BaseDriver.errors.NotYetImplementedError)) {29 console.log('Error is of type NotYetImplementedError');30} else {31 console.log('Error is not of type NotYetImplementedError');32}33const BaseDriver = require('appium-base-driver');34const { isErrorType } = require('appium-base-driver').errors;35const BaseDriver = require('appium-base-driver');36const { isErrorType } =
Using AI Code Generation
1const isErrorType = require('appium-base-driver').errors.isErrorType;2const errors = require('appium-base-driver').errors;3if (isErrorType(e, errors.NoSuchDriverError)) {4}5const isErrorType = require('appium-base-driver').errors.isErrorType;6const errors = require('appium-base-driver').errors;7if (isErrorType(e, errors.NoSuchDriverError)) {8}9const isErrorType = require('appium-base-driver').errors.isErrorType;10const errors = require('appium-base-driver').errors;11if (isErrorType(e, errors.NoSuchDriverError)) {12}13const isErrorType = require('appium-base-driver').errors.isErrorType;14const errors = require('appium-base-driver').errors;15if (isErrorType(e, errors.NoSuchDriverError)) {16}17const isErrorType = require('appium-base-driver').errors.isErrorType;18const errors = require('appium-base-driver').errors;19if (isErrorType(e, errors.NoSuchDriverError)) {20}21const isErrorType = require('appium-base-driver').errors.isErrorType;22const errors = require('appium-base-driver').errors;23if (isErrorType(e, errors.NoSuchDriverError)) {24}25const isErrorType = require('appium-base-driver').errors.isErrorType;26const errors = require('appium-base-driver').errors;27if (isErrorType(e, errors.NoSuchDriverError)) {28}29const isErrorType = require('appium-base-driver').errors.isErrorType;30const errors = require('appium-base-driver').errors;31if (isErrorType(e, errors.NoSuchDriverError)) {
Using AI Code Generation
1const AppiumBaseDriver = require('appium-base-driver');2const errorType = AppiumBaseDriver.errors;3const error = new Error('Error');4console.log(errorType.isErrorType(error, 'Error'));5const appiumSupport = require('appium-support');6const error = new Error('Error');7console.log(appiumSupport.errors.isErrorType(error, 'Error'));
Using AI Code Generation
1const { isErrorType } = require('appium-base-driver/lib/protocol/errors');2const { errors } = require('appium-base-driver');3const errorType = isErrorType(errors.InvalidArgumentError); 4const { isErrorType } = require('appium-base-driver/lib/protocol/errors');5const { errors } = require('appium-base-driver');6const errorType = isErrorType(errors.InvalidArgumentError); 7const { isErrorType } = require('appium-base-driver/lib/protocol/errors');8const { errors } = require('appium-base-driver');9const errorType = isErrorType(errors.InvalidArgumentError); 10const { isErrorType } = require('appium-base-driver/lib/protocol/errors');11const { errors } = require('appium-base-driver');12const errorType = isErrorType(errors.InvalidArgumentError); 13const { isErrorType } = require('appium-base-driver/lib/protocol/errors');14const { errors } = require('appium-base-driver');15const errorType = isErrorType(errors.InvalidArgumentError); 16const { isErrorType } = require('appium-base-driver/lib/protocol/errors');17const { errors } = require('appium-base-driver');18const errorType = isErrorType(errors.InvalidArgumentError); 19const { isErrorType } = require('appium-base-driver
Using AI Code Generation
1const BaseDriver = require('appium-base-driver');2const driver = new BaseDriver();3const error = driver.isErrorType(new Error('Test Error'), 'Test Error');4console.log(error);5isErrorType(error, type)6const BaseDriver = require('appium-base-driver');7const driver = new BaseDriver();8const error = driver.isErrorType(new Error('Test Error'), 'Test Error');9console.log(error);10isSubclassOf(cls)11const BaseDriver = require('appium-base-driver');12const driver = new BaseDriver();13const error = driver.isSubclassOf(BaseDriver);14console.log(error);15isDriver(obj)16const BaseDriver = require('appium-base-driver');17const driver = new BaseDriver();18const error = driver.isDriver(driver);19console.log(error);
Using AI Code Generation
1describe('Test Appium Base Driver', function() {2 it('should return true if error is of type', function() {3 let adb = new ADB();4 let error = new Error('Error');5 let isError = adb.isErrorType(error, 'Error');6 isError.should.be.true;7 });8});9I am new to Appium and have been trying to run tests on Android emulator using Appium. I have a test that is supposed to click on a button and then check if the text of the button has changed. However, the test is failing because the text of the button has not changed. I have tried to use the waitUntil() method but it doesn't seem to be working. I have also tried to use the waitFor() method but it is not available for the Android driver. Does anyone know what is wrong with my code?10describe('Test Button Click', function() {11 it('should click on button and check text', function() {12 let driver = new AndroidDriver();13 driver.init(caps);14 let button = driver.findElementByAccessibilityId('button');15 button.click();16 let buttonText = driver.findElementByAccessibilityId('buttonText');17 buttonText.getText().should.eventually.equal('Button Clicked');18 });19});20class AndroidDriver extends BaseDriver {21 async findElementByAccessibilityId (id) {22 let locator = `-android uiautomator: new UiSelector().description("${id}")`;23 return await this.findElement(locator);24 }25 async click (elementId) {26 let command = ['input', 'tap', elementId];27 return await this.adb.shell(command);28 }29 async getText (elementId) {30 let command = ['dumpsys', 'window', 'windows'];31 let output = await this.adb.shell(command);32 let text = output.match(/mText=.*\n/);33 return text;34 }35 async waitUntil (condition, timeout = 1000, interval = 500) {36 let start = Date.now();37 let end = start + timeout;38 let res = await condition();39 while (res !== true && Date.now() < end) {40 await B.delay(interval);41 res = await condition();42 }43 return res;44 }45 async init (
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!!