Best JavaScript code snippet using appium-base-driver
api.js
Source:api.js
1import Platform from 'Platform'; // eslint-disable-line2import md5 from 'md5';3import Config from 'Config';4/**5 * Request server infomation with https request6 * @param {Object} user7 */8const requestServerInfo = user => {9 const postData = JSON.stringify({10 module: 'chat',11 method: 'login',12 params: [13 user.serverName,14 user.account,15 user.passwordMD5,16 ''17 ],18 v: Config.pkg.version19 });20 return Platform.net.postJSON(user.webServerInfoUrl, {21 headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},22 body: `data=${postData}`23 }).then(data => {24 if (data) {25 user.socketPort = data.chatPort;26 user.token = data.token;27 user.serverVersion = data.version;28 user.socketUrl = data.socketUrl;29 user.uploadFileSize = data.uploadFileSize;30 user.ranzhiUrl = data.ranzhiUrl;31 return Promise.resolve(user);32 }33 return Promise.reject({message: 'Empty serverInfo data', code: 'WRONG_DATA'});34 });35};36/**37 * Check upload file size38 * @param {User} user39 * @param {number} size40 */41const checkUploadFileSize = (user, size) => {42 if (typeof size === 'object') {43 size = size.size;44 }45 const uploadFileSize = user.uploadFileSize;46 return uploadFileSize && size <= uploadFileSize;47};48const getRanzhiServerInfo = (user) => {49 const ranzhiUrl = user.ranzhiUrl;50 if (ranzhiUrl) {51 return Platform.net.getJSON(`${ranzhiUrl}/index.php?mode=getconfig`).then(json => {52 if (json && json.version) {53 json.url = ranzhiUrl;54 json.isPathInfo = json.requestType.toUpperCase() === 'PATH_INFO';55 return Promise.resolve(json);56 }57 return Promise.reject('WRONG_DATA');58 });59 }60 return Promise.reject('RANZHI_SERVER_NOTSET');61};62const API = {63 downloadFile: Platform.net.downloadFile,64 uploadFile: Platform.net.uploadFile,65 requestServerInfo,66 checkUploadFileSize,67 getRanzhiServerInfo,68 checkFileCache: Platform.net.checkFileCache || (() => false)69};70if (DEBUG) {71 global.$.API = API;72}...
net.js
Source:net.js
12var testRemoteFileUrl = "http://dl.dropbox.com/u/12811767/test.pdf";3var testUrl = "www.gft.com";4var testBrowser = new Object();5testBrowser.title = "title";6testBrowser.buttonText = "buttonText";7testBrowser.url = "http://www.google.com";8testBrowser.html = "<html> \9<body> \10<address> \11Written by GFT.com<br /> \12<a href='mailto:barcelona@gft.com'>Email GFT</a><br /> \13Address: Avinguda de la Generalitat 163-167, 08174 Sant Cugat<br /> \14Phone: +34 93 5659-100 \15</address> \16</body> \17</html>";18var testSecondaryBrowserOptions = new Object();19testSecondaryBrowserOptions.Title = "My title";20testSecondaryBrowserOptions.Url = "https://dl.dropboxusercontent.com/u/172657936/HUB_downloads/testwindowopen.html";21testSecondaryBrowserOptions.CloseButtonText = "buttonText2";22testSecondaryBrowserOptions.Html = "<html> \23<body> \24<address> \25Written by GFT.com<br /> \26<a href='mailto:barcelona@gft.com'>Email GFT</a><br /> \27Address: Avinguda de la Generalitat 163-167, 08174 Sant Cugat<br /> \28Phone: +34 93 5659-100 \29</address> \30</body> \31</html>";32var fileExtensions = new Array();33fileExtensions[0] = ".pdf";34testSecondaryBrowserOptions.BrowserFileExtensions = fileExtensions;35//********** UI COMPONENTS36//********** NETWORK TESTCASES37var TestCase_Network = [Appverse.Net,38 [['DownloadFile','{"param1":' + JSON.stringify(testRemoteFileUrl) + '}'],39 ['GetNetworkData',''],40 ['GetNetworkTypeReachable','{"param1":' + JSON.stringify(testUrl) + '}'],41 ['GetNetworkTypeReachableList','{"param1":' + JSON.stringify(testUrl) + '}'],42 ['GetNetworkTypeSupported',''],43 ['IsNetworkReachable','{"param1":' + JSON.stringify(testUrl) + '}'],44 ['OpenBrowser', '{"param1":' + JSON.stringify(testBrowser.title) 45 + ',"param2":' + JSON.stringify(testBrowser.buttonText) 46 + ',"param3":' + JSON.stringify(testBrowser.url) + '}'],47 ['OpenBrowserWithOptions','{"param1":' + JSON.stringify(testSecondaryBrowserOptions) + '}'],48 ['ShowHtml', '{"param1":' + JSON.stringify(testBrowser.title) 49 + ',"param2":' + JSON.stringify(testBrowser.buttonText) 50 + ',"param3":' + JSON.stringify(testBrowser.html) + '}'],51 ['ShowHtmlWithOptions','{"param1":' + JSON.stringify(testSecondaryBrowserOptions) + '}']]];52 ...
shareZs.js
Source:shareZs.js
1// pages/qrcode/shareCode/shareCode.js2import CodeSev from "../../../api/code";3import FormatUtil from "../../../utils/formatUtil";4import Navigation from "../../../utils/navigationUtil";5import BaseUtil from "../../../utils/baseUtil";6import UI from "../../../utils/uiUtil";7import Net from "../../../utils/netUtil";8import StorageUtil from "../../../utils/storageUtil.js";9Page({10 /**11 * 页é¢çåå§æ°æ®12 */13 data: {14 shareImg: ""15 },16 /**17 * çå½å¨æå½æ°--çå¬é¡µé¢å è½½18 */19 onLoad: function (options) {20 21 },22 /**23 * çå½å¨æå½æ°--çå¬é¡µé¢å次渲æå®æ24 */25 onReady: function () {26 Navigation.setNavigationBarTitle("ä¿åå¾çå享");27 UI.loading(true);28 //è·å¾ç¨æ·ä¿¡æ¯29 var data = StorageUtil.getStorageSync('pageData') || {};30 StorageUtil.removeStorageSync('pageData');31 CodeSev.getShareZsQrcode({}, data)32 .then(res => {33 this.setData({34 shareImg: res.bizData35 });36 UI.loading(false);37 }, (err) => {38 UI.loading(false);39 });40 },41 /**42 * çå½å¨æå½æ°--çå¬é¡µé¢å¸è½½43 */44 onUnload: function () {45 },46 _onPreviewImg: function () {47 UI.previewImage({48 urls: [this.data.shareImg]49 });50 },51 /**52 * ä¿åå¾çæ¬å°53 */54 _onSaveImg: function () {55 let params = {56 url: this.data.shareImg57 }58 UI.loading(true);59 Net.downloadFile(params)60 .then(res => {61 let filePath = res.tempFilePath;62 return UI.saveImageToPhotosAlbum({ filePath: filePath });63 })64 .then(res => {65 UI.loading(false);66 UI.alert("该å¾çå·²ç»ä¿åå°æ¨çææºç¸åï¼å¯ä»¥ç´æ¥å»æååå享å¦!");67 }, (err) => {68 UI.loading(false);69 console.log(err);70 UI.alert(err.errMsg);71 });72 }...
localFileUtil.js
Source:localFileUtil.js
1import { request, setConfig, Promise } from '../lib/wx-promise-request';2import CompatibleUtil from "./compatibleUtil";3import Net from "./netUtil";4import Storage from "./storageUtil";5import UI from "./uiUtil";6/**7 * æ¬å°æ件管ç (<=10m)8 * éè¿æ件urlä½ä¸ºkey 9 * abjia10 */11export default class LocalFileUtil {12 /**13 * åå¨ç½ç»æ件å°æ¬å°(é¿æææ)14 * ä¿åæåå tempFile å°ä¸å¯ç¨15 * 16 */17 static saveNetFile(url) {18 return new Promise((resolver, reject) => {19 LocalFileUtil.saveTempFile(url)20 .then(res=>{21 let tempFile = res.tempFilePath;22 wx.saveFile({23 tempFilePath: tempFile,24 success: function (res) {25 resolver(res.savedFilePath)26 },27 fail : function(err){28 //容é微信fileå¤ç29 if (err.errMsg.indexOf("file not exis")){30 resolver("");31 }32 else{33 UI.alert(err.errMsg);34 reject(err); 35 } 36 }37 })38 })39 });40 }41 /**42 * ä¿åå°æ¬å°æ件(临æ¶)43 */44 static saveTempFile(url) {45 return Net.downloadFile({url : url});46 }47 /**48 * å é¤æ¬å°æ件49 */50 static removeFile(localPath) {51 return new Promise((resolver, reject) => {52 wx.removeSavedFile({53 filePath: localPath,54 success: resolver,55 fail: reject56 })57 });58 }59/**60 * è·åæ¬å°æ件信æ¯61 */62 static getFileInfo(localPath,digestAlgorithm) { 63 return new Promise((resolver, reject) => {64 wx.getFileInfo({65 filePath: localPath,66 digestAlgorithm: digestAlgorithm || 'md5',67 success: resolver,68 fail: reject69 })70 });71 }72 73 74 75 76 77 78 ...
fetch-prebuilt-wda.js
Source:fetch-prebuilt-wda.js
...28 await mkdirp(webdriveragentsDir);29 // Define a method that does a streaming download of an asset30 async function downloadAgent (url, targetPath) {31 try {32 await net.downloadFile(url, targetPath);33 } catch (err) {34 throw new Error(`Problem downloading webdriveragent from url ${url}: ${err.message}`);35 }36 }37 log.info(`Downloading assets to: ${webdriveragentsDir}`);38 const agentsDownloading = [];39 for (const asset of releases.assets) {40 const url = asset.browser_download_url;41 log.info(`Downloading: ${url}`);42 try {43 const nameOfAgent = _.last(url.split('/'));44 agentsDownloading.push(downloadAgent(url, path.join(webdriveragentsDir, nameOfAgent)));45 } catch (ign) { }46 }...
library-standard.js
Source:library-standard.js
1import { downloadFile, openFile, getFileExtension, getMimeType, base64Code, base64Encode, base64FileEncode } from '../prelib/work-with-net-standard.js';2let buildArgumentsArray = (argumentsArr) => {3 let args = [];4 for (var i = 0; i < argumentsArr.length; i++) {5 args[i] = argumentsArr[i];6 }7 return args;8}9class WorkWithNet {10 downloadFile() {11 downloadFile(...buildArgumentsArray(arguments));12 }13 openFile() {14 openFile(...buildArgumentsArray(arguments));15 }16 getFileExtension() {17 return getFileExtension(...buildArgumentsArray(arguments));18 }19 getMimeType() {20 return getMimeType(...buildArgumentsArray(arguments));21 }22 base64Code() {23 return base64Code(...buildArgumentsArray(arguments));24 }25 base64Encode() {26 return base64Encode(...buildArgumentsArray(arguments));27 }28 base64FileEncode() {29 return base64FileEncode(...buildArgumentsArray(arguments));30 }31}32const workWithNet = new WorkWithNet();33export default workWithNet;...
library.js
Source:library.js
1import { downloadFile, openFile, getFileExtension, getMimeType, base64Code, base64Encode, base64FileEncode } from '../prelib/work-with-net.js';2let buildArgumentsArray = (argumentsArr) => {3 let args = [];4 for (var i = 0; i < argumentsArr.length; i++) {5 args[i] = argumentsArr[i];6 }7 return args;8}9class WorkWithNet {10 downloadFile() {11 downloadFile(...buildArgumentsArray(arguments));12 }13 openFile() {14 openFile(...buildArgumentsArray(arguments));15 }16 getFileExtension() {17 return getFileExtension(...buildArgumentsArray(arguments));18 }19 getMimeType() {20 return getMimeType(...buildArgumentsArray(arguments));21 }22 base64Code() {23 return base64Code(...buildArgumentsArray(arguments));24 }25 base64Encode() {26 return base64Encode(...buildArgumentsArray(arguments));27 }28 base64FileEncode() {29 return base64FileEncode(...buildArgumentsArray(arguments));30 }31}32const workWithNet = new WorkWithNet();33export default workWithNet;...
config.js
Source:config.js
1const webName = "/baoming";2const req_path = "/net/requestHandle.do";3const config = {4 webName:webName,5 req_path:req_path,6 url_proj:window.location.protocol+"//"+window.location.host+webName,7 url_base:window.location.protocol+"//"+window.location.host+webName+req_path,8 url_base2:window.location.protocol+"//"+window.location.host+webName+"/net/updateFile.do",9 url_transferFile:window.location.protocol+"//"+window.location.host+webName+"/net/transferFile.do",10 url_baseDownload:window.location.protocol+"//"+window.location.host+webName+"/net/downloadFile.do",11 url_baseDelete:window.location.protocol+"//"+window.location.host+webName+"/net/deleteFile.do",12 url_import:window.location.protocol+"//"+window.location.host+webName+"/net/readXls.do",13 url_export:window.location.protocol+"//"+window.location.host+webName+"/net/writeXls.do",14 everyPage:parseInt((window.innerHeight-208)/53),15}...
Using AI Code Generation
1}).build();2driver.executeScript("mobile: downloadFile", {3}).then(function (response) {4 console.log(response);5 driver.quit();6}).done();7{8 "value": {9 }10}11import io.appium.java_client.AppiumDriver;12import io.appium.java_client.android.AndroidDriver;13import org.openqa.selenium.remote.DesiredCapabilities;14import java.net.URL;15import java.net.MalformedURLException;16import java.util.concurrent.TimeUnit;17import org.openqa.selenium.remote.Response;18import org.openqa.selenium.remote.Command;19import org.openqa.selenium.remote.DriverCommand;20import org.openqa.selenium.remote.HttpCommandExecutor;21public class test {22 public static void main(String[] args) {23 DesiredCapabilities capabilities = new DesiredCapabilities();24 capabilities.setCapability("platformName", "Android");25 capabilities.setCapability("platformVersion", "4.4");26 capabilities.setCapability("deviceName", "Android Emulator");27 URL url;28 try {
Using AI Code Generation
1var net = require('net');2var fs = require('fs');3var options = {4 headers: {5 }6};7var req = net.request(options, function(res) {8 console.log('STATUS: ' + res.statusCode);9 console.log('HEADERS: ' + JSON.stringify(res.headers));10 res.setEncoding('utf8');11 res.on('data', function (chunk) {12 console.log('BODY: ' + chunk);13 });14});15req.write(JSON.stringify({path: '/sdcard/Download/test.png'}));16req.end();
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!!