Best JavaScript code snippet using appium-android-driver
ah1.js
Source: ah1.js
...585 return;586 }587 const activeHandlers = await server.getWebSocketHandlers(sessionId);588 for (const pathname of _.keys(activeHandlers)) {589 await server.removeWebSocketHandler(pathname);590 }591};592/**593 * Takes a desired capability and tries to JSON.parse it as an array,594 * and either returns the parsed array or a singleton array.595 *596 * @param {any} cap A desired capability597 */598helpers.parseArray = function (cap) {599 let parsedCaps;600 try {601 parsedCaps = JSON.parse(cap);602 } catch (ign) { }603 if (_.isArray(parsedCaps)) {...
android-helpers.js
Source: android-helpers.js
...536 return;537 }538 const activeHandlers = await server.getWebSocketHandlers(sessionId);539 for (const pathname of _.keys(activeHandlers)) {540 await server.removeWebSocketHandler(pathname);541 }542};543/**544 * Takes a desired capability and tries to JSON.parse it as an array,545 * and either returns the parsed array or a singleton array.546 *547 * @param {any} cap A desired capability548 */549helpers.parseArray = function (cap) {550 let parsedCaps;551 try {552 parsedCaps = JSON.parse(cap);553 } catch (ign) { }554 if (_.isArray(parsedCaps)) {...
utils.js
Source: utils.js
...327 return;328 }329 const activeHandlers = await server.getWebSocketHandlers(sessionId);330 for (const pathname of _.keys(activeHandlers)) {331 await server.removeWebSocketHandler(pathname);332 }333}334/**335 * Returns true if the urlString is localhost336 * @param {?string} urlString337 * @returns {boolean} Return true if the urlString is localhost338 */339function isLocalHost (urlString) {340 try {341 const {hostname} = url.parse(urlString);342 return ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(hostname);343 } catch (ign) {344 log.warn(`'${urlString}' cannot be parsed as a valid URL`);345 }...
log.js
Source: log.js
...112 if (_.isEmpty(await this.server.getWebSocketHandlers(pathname))) {113 return;114 }115 log.debug('Stopping the system logs broadcasting web socket server');116 await this.server.removeWebSocketHandler(pathname);117};...
server.js
Source: server.js
1import path from 'path';2import express from 'express';3import http from 'http';4import favicon from 'serve-favicon';5import bodyParser from 'body-parser';6import methodOverride from 'method-override';7import log from './logger';8import { startLogFormatter, endLogFormatter } from './express-logging';9import { allowCrossDomain, fixPythonContentType, defaultToJSONContentType,10 catchAllHandler, catch404Handler, catch4XXHandler,11 allowCrossDomainAsyncExecute} from './middleware';12import { guineaPig, guineaPigScrollable, guineaPigAppBanner, welcome, STATIC_DIR } from './static';13import { produceError, produceCrash } from './crash';14import { addWebSocketHandler, removeWebSocketHandler, removeAllWebSocketHandlers,15 getWebSocketHandlers } from './websocket';16import B from 'bluebird';17async function server (configureRoutes, port, hostname = null, allowCors = true) {18 // create the actual http server19 const app = express();20 let httpServer = http.createServer(app);21 httpServer.addWebSocketHandler = addWebSocketHandler;22 httpServer.removeWebSocketHandler = removeWebSocketHandler;23 httpServer.removeAllWebSocketHandlers = removeAllWebSocketHandlers;24 httpServer.getWebSocketHandlers = getWebSocketHandlers;25 // http.Server.close() only stops new connections, but we need to wait until26 // all connections are closed and the `close` event is emitted27 const close = httpServer.close.bind(httpServer);28 httpServer.close = async () => {29 return await new B((resolve, reject) => {30 httpServer.on('close', resolve);31 close((err) => {32 if (err) reject(err); // eslint-disable-line curly33 });34 });35 };36 return await new B((resolve, reject) => {37 httpServer.on('error', (err) => {38 if (err.code === 'EADDRNOTAVAIL') {39 log.error('Could not start REST http interface listener. ' +40 'Requested address is not available.');41 } else {42 log.error('Could not start REST http interface listener. The requested ' +43 'port may already be in use. Please make sure there is no ' +44 'other instance of this server running already.');45 }46 reject(err);47 });48 httpServer.on('connection', (socket) => {49 socket.setTimeout(600 * 1000); // 10 minute timeout50 socket.on('error', reject);51 });52 configureServer(app, configureRoutes, allowCors);53 let serverArgs = [port];54 if (hostname) {55 // If the hostname is omitted, the server will accept56 // connections on any IP address57 serverArgs.push(hostname);58 }59 httpServer.listen(...serverArgs, (err) => {60 if (err) {61 reject(err);62 }63 resolve(httpServer);64 });65 });66}67function configureServer (app, configureRoutes, allowCors = true) {68 app.use(endLogFormatter);69 // set up static assets70 app.use(favicon(path.resolve(STATIC_DIR, 'favicon.ico')));71 app.use(express.static(STATIC_DIR));72 // crash routes, for testing73 app.use('/wd/hub/produce_error', produceError);74 app.use('/wd/hub/crash', produceCrash);75 // add middlewares76 if (allowCors) {77 app.use(allowCrossDomain);78 } else {79 app.use(allowCrossDomainAsyncExecute);80 }81 app.use(fixPythonContentType);82 app.use(defaultToJSONContentType);83 app.use(bodyParser.urlencoded({extended: true}));84 app.use(methodOverride());85 app.use(catch4XXHandler);86 app.use(catchAllHandler);87 // make sure appium never fails because of a file size upload limit88 app.use(bodyParser.json({limit: '1gb'}));89 // set up start logging (which depends on bodyParser doing its thing)90 app.use(startLogFormatter);91 configureRoutes(app);92 // dynamic routes for testing, etc.93 app.all('/welcome', welcome);94 app.all('/test/guinea-pig', guineaPig);95 app.all('/test/guinea-pig-scrollable', guineaPigScrollable);96 app.all('/test/guinea-pig-app-banner', guineaPigAppBanner);97 // catch this last, so anything that falls through is 404ed98 app.use(catch404Handler);99}...
websockets-e2e-specs.js
Source: websockets-e2e-specs.js
1import _ from 'lodash';2import { server, routeConfiguringFunction,3 DEFAULT_WS_PATHNAME_PREFIX } from '../..';4import { FakeDriver } from '../protocol/fake-driver';5import chai from 'chai';6import chaiAsPromised from 'chai-as-promised';7import WebSocket from 'ws';8import B from 'bluebird';9chai.use(chaiAsPromised);10describe('Websockets (e2e)', function () {11 let baseServer;12 let driver;13 const SESSION_ID = 'foo';14 const WS_DATA = 'Hello';15 const PORT = 8181;16 before(async function () {17 driver = new FakeDriver();18 driver.sessionId = SESSION_ID;19 baseServer = await server({20 routeConfiguringFunction: routeConfiguringFunction(driver),21 port: PORT,22 });23 });24 after(async function () {25 await baseServer.close();26 });27 describe('web sockets support', function () {28 it('should be able to add websocket handler and remove it', async function () {29 const wss = new WebSocket.Server({30 noServer: true,31 });32 wss.on('connection', (ws) => {33 if (ws && ws.readyState === WebSocket.OPEN) {34 ws.send(WS_DATA);35 }36 });37 const previousListenerCount = baseServer.listenerCount('upgrade');38 const endpoint = `${DEFAULT_WS_PATHNAME_PREFIX}/hello`;39 const timeout = 5000;40 await baseServer.addWebSocketHandler(endpoint, wss);41 baseServer.listenerCount('upgrade').should.be.above(previousListenerCount);42 _.keys(await baseServer.getWebSocketHandlers()).length.should.eql(1);43 await new B((resolve, reject) => {44 const client = new WebSocket(`ws://localhost:${PORT}${endpoint}`);45 client.on('connection', (ws, req) => {46 ws.should.not.be.empty;47 req.connection.remoteAddress.should.not.be.empty;48 });49 client.on('message', (data) => {50 data.toString().should.eql(WS_DATA);51 resolve();52 });53 client.on('error', reject);54 setTimeout(() => reject(new Error('No websocket messages have been received after the timeout')),55 timeout);56 });57 (await baseServer.removeWebSocketHandler(endpoint)).should.be.true;58 _.keys(await baseServer.getWebSocketHandlers()).length.should.eql(0);59 await new B((resolve, reject) => {60 const client = new WebSocket(`ws://localhost:${PORT}${endpoint}`);61 client.on('message', (data) =>62 reject(new Error(`No websocket messages are expected after the handler ` +63 `has been removed. '${data?.toString()}' is received instead. `))64 );65 client.on('error', resolve);66 setTimeout(resolve, timeout);67 });68 baseServer.listenerCount('upgrade').should.be.above(previousListenerCount);69 });70 });...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10var webdriver = require('selenium-webdriver'),11 until = webdriver.until;12var driver = new webdriver.Builder()13 .forBrowser('chrome')14 .build();15driver.findElement(By.name('q')).sendKeys('webdriver');16driver.findElement(By.name('btnG')).click();17driver.wait(until.titleIs('webdriver - Google Search'), 1000);18driver.quit();
Using AI Code Generation
1server.removeWebSocketHandler("test");2server.addWebSocketHandler("test", new WebSocketHandler() {3 public void onMessage(WebSocket webSocket, String text) {4 webSocket.send("Hello, it's Appium!");5 }6 public void onMessage(WebSocket webSocket, ByteString bytes) {7 webSocket.send("Hello, it's Appium!");8 }9 public void onOpen(WebSocket webSocket, Request request) {10 webSocket.send("Hello, it's Appium!");11 }12 public void onClosing(WebSocket webSocket, int code, String reason) {13 webSocket.close(1000, null);14 }15 public void onClosed(WebSocket webSocket, int code, String reason) {16 webSocket.close(1000, null);17 }18 public void onFailure(WebSocket webSocket, Throwable t, Response response) {19 webSocket.close(1000, null);20 }21});22server.removeWebSocketHandler("test");
Using AI Code Generation
1var wd = require('wd');2var asserters = wd.asserters;3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6var expect = chai.expect;7var should = chai.should();8var serverConfig = {9};10var desiredCaps = {11};12var driver = wd.promiseChainRemote(serverConfig);13describe('Appium Android Driver', function() {14 this.timeout(300000);15 before(function() {16 var desired = desiredCaps;17 .init(desired)18 .setImplicitWaitTimeout(60000);19 });20 after(function() {21 return driver.quit();22 });23 it('should remove websocket handler', function() {24 .removeWebSocketHandler('/wd/hub/session/:sessionId/appium/device/lock')25 .then(function() {26 .lockDevice()27 .should.be.rejectedWith('Not Found');28 });29 });30});31info: [debug] [ADB] 1 device(s) connected32info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"id","
Using AI Code Generation
1var wd = require("wd");2var assert = require('assert');3var server = require('webdriverio').remote({desiredCapabilities:{browserName:'chrome'}}).init();4var desired = {5};6var driver = wd.promiseChainRemote("localhost", 4723);7 .init(desired)8 .elementById("lst-ib")9 .sendKeys("Hello World!")10 .elementById("lst-ib")11 .sendKeys(wd.SPECIAL_KEYS["Enter"])12 .elementByClassName("r")13 .text()14 .then(function(text) {15 assert(text === "Hello World!");16 })17 .quit();18server.removeWebSocketHandler('/wd/hub/session/:sessionId/element/:id/value');19server.removeWebSocketHandler('/wd/hub/session/:sessionId/element/:id/click');20server.removeWebSocketHandler('/wd/hub/session/:sessionId/element/:id/text');21 .init(desired)22 .elementById("lst-ib")23 .sendKeys("Hello World!")24 .elementById("lst-ib")25 .sendKeys(wd.SPECIAL_KEYS["Enter"])26 .elementByClassName("r")27 .text()28 .then(function(text) {29 assert(text === "Hello World!");30 })31 .quit();32driver.quit();
Check out the latest blogs from LambdaTest on this topic:
Mobile apps have been an inseparable part of daily lives. Every business wants to be part of the ever-growing digital world and stay ahead of the competition by developing unique and stable applications.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
Let’s put it short: Appium Desktop = Appium Server + Inspector. When Appium Server runs automation test scripts, Appium Inspector can identify the UI elements of every application under test. The core structure of an Appium Inspector is to ensure that you discover every visible app element when you develop your test scripts. Before you kickstart your journey with Appium Inspector, you need to understand the details of it.
Mobile devices and mobile applications – both are booming in the world today. The idea of having the power of a computer in your pocket is revolutionary. As per Statista, mobile accounts for more than half of the web traffic worldwide. Mobile devices (excluding tablets) contributed to 54.4 percent of global website traffic in the fourth quarter of 2021, increasing consistently over the past couple of years.
Before we discuss the Joomla testing, let us understand the fundamentals of Joomla and how this content management system allows you to create and maintain web-based applications or websites without having to write and implement complex coding requirements.
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!!