Best JavaScript code snippet using appium
file-movement-specs.js
Source:file-movement-specs.js  
1"use strict";2var setup = require("../common/setup-base")3  , env = require('../../helpers/env')4  , getAppPath = require('../../helpers/app').getAppPath5  , fs = require('fs')6  , path = require('path')7  , Readable = require('stream').Readable8  , Simulator = require('../../../lib/devices/ios/simulator.js')9  , xcode = require('../../../lib/devices/ios/xcode.js')10  , exec = require('child_process').exec11  , getSimUdid = require('../../helpers/sim-udid.js').getSimUdid12  , Unzip = require('unzip');13describe('file movements - pullFile and pushFile', function () {14  var driver;15  var desired = {16    app: getAppPath('TestApp')17  };18  setup(this, desired).then(function (d) { driver = d; });19  it('should not be able to fetch a file from the file system at large', function (done) {20    driver21      .pullFile(__filename)22      .should.be.rejected23    .nodeify(done);24  });25  it('should be able to fetch the Address book', function (done) {26    driver27      .pullFile('Library/AddressBook/AddressBook.sqlitedb')28      .then(function (data) {29        var stringData = new Buffer(data, 'base64').toString();30        return stringData.indexOf('SQLite').should.not.equal(-1);31      })32    .nodeify(done);33  });34  it('should not be able to fetch something that does not exist', function (done) {35    driver36      .pullFile('Library/AddressBook/nothere.txt')37      .should.eventually.be.rejectedWith(/13/)38    .nodeify(done);39  });40  it('should be able to push and pull a file', function (done) {41    var stringData = "random string data " + Math.random();42    var base64Data = new Buffer(stringData).toString('base64');43    var remotePath = 'Library/AppiumTest/remote.txt';44    driver45      .pushFile(remotePath, base64Data)46      .pullFile(remotePath)47      .then(function (remoteData64) {48        var remoteData = new Buffer(remoteData64, 'base64').toString();49        remoteData.should.equal(stringData);50      })51      .nodeify(done);52  });53  describe('for a .app @skip-ci', function () {54    // TODO: skipping ci because of local files use, to review.55    var fileContent = "IAmTheVeryModelOfAModernMajorTestingTool";56    var fileName = "someFile.tmp";57    var fullPath = "";58    before(function (done) {59      var pv = env.CAPS.platformVersion || '7.1';60      var ios8 = parseFloat(pv) >= 8;61      xcode.getiOSSDKVersion(function (err, sdk) {62        if (err) return done(err);63        var next = function (udid) {64          var sim = new Simulator({65            platformVer: pv,66            sdkVer: sdk,67            udid: udid68          });69          var simRoots = sim.getDirs();70          if (simRoots.length < 1) {71            return done(new Error("Didn't find any simulator directories"));72          }73          var basePath;74          if (ios8) {75            // ios8 apps are stored in a different directory structure, need76            // to navigate down a few more here77            basePath = path.resolve(simRoots[0], 'Containers', 'Bundle',78                                       'Application');79          } else {80            basePath = path.resolve(simRoots[0], 'Applications');81          }82          basePath = basePath.replace(/\s/g, '\\ ');83          var findCmd = 'find ' + basePath + ' -name "TestApp.app"';84          exec(findCmd, function (err, stdout) {85            if (err) return done(err);86            if (!stdout) return done(new Error("Could not find testapp.app"));87            var appRoot = stdout.replace(/\n$/, '');88            fullPath = path.resolve(appRoot, fileName);89            fs.writeFile(fullPath, fileContent, done);90          });91        };92        if (parseFloat(sdk) >= 8) {93          getSimUdid('6', sdk, env.CAPS, function (err, udid) {94            if (err) return done(err);95            next(udid);96          });97        } else {98          next();99        }100      });101    });102    it('should be able to fetch a file from the app directory', function (done) {103      var arg = path.resolve('/TestApp.app', fileName);104      driver105        .pullFile(arg)106        .then(function (data) {107          var stringData = new Buffer(data, 'base64').toString();108          return stringData.should.equal(fileContent);109        })110        .nodeify(done);111    });112  });113  describe('file movements - pullFolder', function () {114    it('should pull all the files in Library/AddressBook', function (done) {115      var entryCount = 0;116      driver117        .pullFolder('Library/AddressBook')118        .then(function (data) {119          var zipStream = new Readable();120          zipStream._read = function noop() {};121          zipStream122            .pipe(Unzip.Parse())123            .on('entry', function (entry) {124              entryCount++;125              entry.autodrain();126            })127            .on('close', function () {128              entryCount.should.be.above(1);129              done();130            });131          zipStream.push(data, 'base64');132          zipStream.push(null);133        });134    });135    it('should not pull folders from file system', function (done) {136      driver137        .pullFolder(__dirname)138          .should.be.rejected139        .nodeify(done);140    });141    it('should not be able to fetch a folder that does not exist', function (done) {142      driver143        .pullFolder('Library/Rollodex')144          .should.eventually.be.rejectedWith(/13/)145        .nodeify(done);146    });147  });...file-actions-specs.js
Source:file-actions-specs.js  
...25        .withArgs(localFile)26        .returns(Buffer.from('YXBwaXVt', 'utf8'));27      sandbox.stub(support.fs, 'exists').withArgs(localFile).returns(true);28      sandbox.stub(support.fs, 'unlink');29      await driver.pullFile('remote_path').should.become('YXBwaXVt');30      driver.adb.pull.calledWithExactly('remote_path', localFile)31        .should.be.true;32      support.fs.unlink.calledWithExactly(localFile).should.be.true;33    });34    it('should be able to pull file located in application container from the device', async function () {35      let localFile = 'local/tmp_file';36      const packageId = 'com.myapp';37      const remotePath = 'path/in/container';38      const tmpPath = '/data/local/tmp/container';39      sandbox.stub(support.tempDir, 'path').returns(localFile);40      sandbox.stub(driver.adb, 'pull');41      sandbox.stub(driver.adb, 'shell');42      sandbox.stub(support.util, 'toInMemoryBase64')43        .withArgs(localFile)44        .returns(Buffer.from('YXBwaXVt', 'utf8'));45      sandbox.stub(support.fs, 'exists').withArgs(localFile).returns(true);46      sandbox.stub(support.fs, 'unlink');47      await driver.pullFile(`@${packageId}/${remotePath}`).should.become('YXBwaXVt');48      driver.adb.pull.calledWithExactly(tmpPath, localFile).should.be.true;49      driver.adb.shell.calledWithExactly(['run-as', packageId, `chmod 777 '/data/data/${packageId}/${remotePath}'`]).should.be.true;50      driver.adb.shell.calledWithExactly(['cp', '-f', `/data/data/${packageId}/${remotePath}`, tmpPath]).should.be.true;51      support.fs.unlink.calledWithExactly(localFile).should.be.true;52      driver.adb.shell.calledWithExactly(['rm', '-f', tmpPath]).should.be.true;53    });54  });55  describe('pushFile', function () {56    it('should be able to push file to device', async function () {57      let localFile = 'local/tmp_file';58      let content = 'appium';59      sandbox.stub(support.tempDir, 'path').returns(localFile);60      sandbox.stub(driver.adb, 'push');61      sandbox.stub(driver.adb, 'shell');...file-movement-e2e-specs.js
Source:file-movement-e2e-specs.js  
...18    after(async function () {19      await deleteSession();20    });21    async function pullFileAsString (remotePath) {22      let remoteData64 = await driver.pullFile(remotePath);23      return Buffer.from(remoteData64, 'base64').toString();24    }25    describe('sim relative', function () {26      describe('files', function () {27        it('should not be able to fetch a file from the file system at large', async function () {28          await driver.pullFile(__filename).should.eventually.be.rejected;29        });30        it('should be able to fetch the Address book', async function () {31          let stringData = await pullFileAsString(`${UICAT_CONTAINER}/PkgInfo`);32          stringData.indexOf('APPL').should.not.equal(-1);33        });34        it('should not be able to fetch something that does not exist', async function () {35          await driver.pullFile('Library/AddressBook/nothere.txt')36            .should.eventually.be.rejectedWith(/13/);37        });38        it('should be able to push and pull a file', async function () {39          let stringData = `random string data ${Math.random()}`;40          let base64Data = Buffer.from(stringData).toString('base64');41          let remotePath = `${UICAT_CONTAINER}/remote.txt`;42          await driver.pushFile(remotePath, base64Data);43          let remoteStringData = await pullFileAsString(remotePath);44          remoteStringData.should.equal(stringData);45        });46      });47      describe('folders', function () {48        it('should not pull folders from file system', async function () {49          await driver.pullFolder(__dirname).should.eventually.be.rejected;...dowload.image.android.emulator.spec.js
Source:dowload.image.android.emulator.spec.js  
...54        expect(fileExists(filePath)).toEqual(false);55        // Pull the file from the device, it was uploaded in the before step56        // This is the `tricky` part, you need to know the file structure of the device and where you can download57        // the file from. I've checked this structure with the VUSB offering of Sauce Labs for private devices.58        const downloadedBase64Image = driver.pullFile(deviceFilePath);59        // Write the file to the file the correct folder60        writeFileSync(filePath, downloadedBase64Image, 'base64');61        // Now verify that the file does exist in our repo62        expect(fileExists(filePath)).toEqual(true);63    });...dowload.image.android.simulator.spec.js
Source:dowload.image.android.simulator.spec.js  
...54        expect(fileExists(filePath)).toEqual(false);55        // Pull the file from the device, it was uploaded in the before step56        // This is the `tricky` part, you need to know the file structure of the device and where you can download57        // the file from. I've checked this structure with the VUSB offering of Sauce Labs for private devices.58        const downloadedBase64Image = driver.pullFile(deviceFilePath);59        // Write the file to the file the correct folder60        writeFileSync(filePath, downloadedBase64Image, 'base64');61        // Now verify that the file does exist in our repo62        expect(fileExists(filePath)).toEqual(true);63    });...dowload.image.android.real.spec.js
Source:dowload.image.android.real.spec.js  
...50        expect(fileExists(filePath)).toEqual(false);51        // Pull the file from the device, it was uploaded in the before step52        // This is the `tricky` part, you need to know the file structure of the device and where you can download53        // the file from. I've checked this structure with the VUSB offering of Sauce Labs for private devices.54        const downloadedBase64Image = driver.pullFile(deviceFilePath);55        // Write the file to the file the correct folder56        writeFileSync(filePath, downloadedBase64Image, 'base64');57        // Now verify that the file does exist in our repo58        expect(fileExists(filePath)).toEqual(true);59    });...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.takeScreenshot().then(10  function(image, err) {11    require('fs').writeFile('out.png', image, 'base64', function(err) {12      console.log(err);13    });14  }15);16driver.quit();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();10driver.pullFile('/sdcard/example.txt').then(function (res) {11    console.log(res);12});13driver.pullFolder('/sdcard/example_folder').then(function (res) {14    console.log(res);15});16driver.pushFile('/sdcard/example.txt', 'Hello World!').then(function () {17    console.log('File created');18});19driver.pushFolder('/sdcard/example_folder').then(function () {20    console.log('Folder created');21});22var webdriver = require('selenium-webdriver'),23    until = webdriver.until;24var driver = new webdriver.Builder()25    .forBrowser('chrome')26    .build();27driver.findElement(By.name('q')).sendKeys('webdriver');28driver.findElement(By.name('btnG')).click();29driver.wait(until.titleIs('webdriver - Google Search'), 1000);30driver.quit();31driver.pullFile('/sdcard/example.txt').then(function (res) {32    console.log(res);33});34driver.pullFolder('/sdcard/example_folder').then(function (res) {35    console.log(res);36});37driver.pushFile('/sdcard/example.txt', 'Hello World!').then(function () {38    console.log('File created');39});40driver.pushFolder('/sdcard/example_folder').then(function () {41    console.log('Folder created');42});43var webdriver = require('selenium-webdriver'),44    until = webdriver.until;45var driver = new webdriver.Builder()46    .forBrowser('chrome')47    .build();48driver.findElement(By.name('q')).sendKeys('webdriver');49driver.findElement(By.name('btnG')).click();50driver.wait(until.titleIs('webdriver - Google Search'), 1000);51driver.quit();Using AI Code Generation
1var wd = require('wd');2var driver = wd.promiseChainRemote("localhost", 4723);3var desiredCaps = {4};5driver.init(desiredCaps)6  .then(function() {7    return driver.pullFile('/data/data/com.example.myapp/files/test.txt');8  })9  .then(function(data) {10    console.log(data);11  })12  .fin(function() { return driver.quit(); })13  .done();Using AI Code Generation
1describe('Test Appium', function () {2    this.timeout(300000);3    var driver;4    before(function () {5        driver = webdriverio.remote({6            desiredCapabilities: {7            },Using AI Code Generation
1var fs = require('fs');2var driver = require('./driver.js').driver;3driver.pullFile('/storage/emulated/0/DCIM/100MEDIA/IMG_20160324_162738.jpg').then(function (data) {4    console.log(data);5    var base64Data = data.replace(/^data:image\/png;base64,/, "");6    fs.writeFile("out.png", base64Data, 'base64', function(err) {7        console.log(err);8    });9});10var fs = require('fs');11var driver = require('./driver.js').driver;12driver.pushFile('/storage/emulated/0/DCIM/100MEDIA/IMG_20160324_162738.jpg', fs.readFileSync('out.png')).then(function (data) {13    console.log(data);14});15var driver = require('./driver.js').driver;16driver.installApp('/Users/jagadeesh/Downloads/ContactManager.apk').then(function (data) {17    console.log(data);18});19var driver = require('./driver.js').driver;20driver.removeApp('com.example.android.contactmanager').then(function (data) {21    console.log(data);22});23var driver = require('./driver.js').driver;24driver.launchApp().then(function (data) {Using AI Code Generation
1driver.pullFile('/sdcard/Download/test.txt')2.then(function (data) {3    console.log(data);4})5.catch(function (err) {6    console.log(err);7});8var fs = require('fs');9var data = fs.readFileSync('test.txt', 'utf8');10driver.pushFile('/sdcard/Download/test.txt', data)11.then(function () {12    console.log('File pushed successfully');13})14.catch(function (err) {15    console.log(err);16});17driver.getDeviceTime()18.then(function (time) {19    console.log(time);20})21.catch(function (err) {22    console.log(err);23});24driver.getPerformanceData('com.example.android.apis', 'cpuinfo', 1000)25.then(functionLearn 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!!
