Best JavaScript code snippet using appium-android-driver
actions-specs.js
Source:actions-specs.js  
...423    });424    it('should be able to take screenshot via exec-out (API level > 20)', async function () {425      driver.adb.getApiLevel.returns(24);426      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);427      await driver.getScreenshot().should.become('YXBwaXVt');428      driver.getScreenshotDataWithAdbExecOut.calledOnce.should.be.true;429      driver.getScreenshotDataWithAdbShell.notCalled.should.be.true;430      image.getBuffer.calledWith(jimp.MIME_PNG).should.be.true;431    });432    it('should be able to take screenshot via adb shell (API level <= 20)', async function () {433      driver.adb.getApiLevel.returns(20);434      driver.getScreenshotDataWithAdbShell.withArgs(driver.adb, driver.opts).returns(image);435      await driver.getScreenshot().should.become('YXBwaXVt');436      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;437      driver.getScreenshotDataWithAdbExecOut.notCalled.should.be.true;438      image.getBuffer.calledWith(jimp.MIME_PNG).should.be.true;439    });440    it('should tries to take screenshot via adb shell if exec-out failed (API level > 20)', async function () {441      driver.adb.getApiLevel.returns(24);442      driver.getScreenshotDataWithAdbExecOut.throws();443      driver.getScreenshotDataWithAdbShell.withArgs(driver.adb, driver.opts).returns(image);444      await driver.getScreenshot().should.become('YXBwaXVt');445      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;446      driver.getScreenshotDataWithAdbShell.calledOnce.should.be.true;447    });448    it('should throw error if adb shell failed', async function () {449      driver.adb.getApiLevel.returns(20);450      driver.getScreenshotDataWithAdbShell.throws();451      await driver.getScreenshot().should.be.rejectedWith('Cannot get screenshot');452    });453    it('should rotate image if API level < 23', async function () {454      driver.adb.getApiLevel.returns(22);455      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);456      await driver.getScreenshot();457      driver.adb.getScreenOrientation.calledOnce.should.be.true;458      image.rotate.calledOnce.should.be.true;459    });460    it('should not rotate image if API level >= 23', async function () {461      driver.adb.getApiLevel.returns(23);462      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);463      await driver.getScreenshot();464      driver.adb.getScreenOrientation.notCalled.should.be.true;465      image.rotate.notCalled.should.be.true;466    });467    it('should not throws error if rotate image failed', async function () {468      image.rotate.resetBehavior();469      image.rotate.throws();470      driver.adb.getApiLevel.returns(22);471      driver.getScreenshotDataWithAdbExecOut.withArgs(driver.adb).returns(image);472      await driver.getScreenshot().should.be.fulfilled;473      image.rotate.threw().should.be.true;474    });475  });...baiduTest.spec.js
Source:baiduTest.spec.js  
...137                    let filepath = self.screenshotPath + '/' + self.caseName + '_' + self.stepId;138                    let driver = self.driver;139                    try{140                        // catch error when get alert msg141                        await driver.getScreenshot(filepath + '.png');142                        let url = await driver.url();143                        let html = await driver.source();144                        html = '<!--url: '+url+' -->\n' + html;145                        fs.writeFileSync(filepath + '.html', html);146                        let cookies = await driver.cookies();147                        fs.writeFileSync(filepath + '.cookie', JSON.stringify(cookies));148                    }149                    catch(e){}150                }151            });152            after(function(){153                return this.driver.close();154            });155        });...screenshots-specs.js
Source:screenshots-specs.js  
...22      });23      it('should get a screenshot from WDA if no errors are detected', async function () {24        proxyStub.returns(base64Response);25        driver.opts.realDevice = false;26        await driver.getScreenshot();27        proxyStub.calledOnce.should.be.true;28        proxyStub.firstCall.args[0].should.eql('/screenshot');29        proxyStub.firstCall.args[1].should.eql('GET');30        simctlStub.notCalled.should.be.true;31      });32      it('should get a screenshot from simctl if WDA call fails and Xcode version >= 8.1', async function () {33        proxyStub.returns(null);34        simctlStub.returns(base64Response);35        driver.opts.realDevice = false;36        driver.xcodeVersion = {37          versionFloat: 8.338        };39        const result = await driver.getScreenshot();40        result.should.equal(base64Response);41        proxyStub.calledOnce.should.be.true;42        simctlStub.calledOnce.should.be.true;43      });44    });45    describe('real device', function () {46      it('should get a screenshot from WDA if no errors are detected', async function () {47        proxyStub.returns(base64Response);48        driver.opts.realDevice = true;49        await driver.getScreenshot();50        proxyStub.calledOnce.should.be.true;51        proxyStub.firstCall.args[0].should.eql('/screenshot');52        proxyStub.firstCall.args[1].should.eql('GET');53      });54      describe('idevicescreenshot', function () {55        const tiffPath = '/some/file.tiff';56        const pngPath = '/some/file.png';57        const udid = '1234';58        const toolName = 'idevicescreenshot';59        const pngFileContent = 'blabla';60        let fsExistsStub;61        let fsWhichStub;62        let fsRimRafStub;63        let fsReadFileStub;64        let execStub;65        let pathStub;66        beforeEach(function () {67          driver.opts.realDevice = true;68          driver.opts.udid = udid;69        });70        afterEach(function () {71          for (const stub of [fsExistsStub, fsWhichStub, fsReadFileStub, fsRimRafStub, execStub, pathStub]) {72            if (stub) {73              stub.restore();74            }75          }76        });77        describe('success', function () {78          beforeEach(function () {79            fsExistsStub = sinon.stub(fs, 'exists');80            fsExistsStub.returns(true);81            fsWhichStub = sinon.stub(fs, 'which');82            fsWhichStub.returns(toolName);83            fsRimRafStub = sinon.stub(fs, 'rimraf');84            fsReadFileStub = sinon.stub(fs, 'readFile');85            fsReadFileStub.returns(pngFileContent);86            execStub = sinon.stub(teenProcessModule, 'exec');87            pathStub = sinon.stub(tempDir, 'path');88            pathStub.withArgs({prefix: `screenshot-${udid}`, suffix: '.tiff'}).returns(tiffPath);89            pathStub.withArgs({prefix: `screenshot-${udid}`, suffix: '.png'}).returns(pngPath);90          });91          afterEach(function () {92            fsWhichStub.calledOnce.should.be.true;93            fsWhichStub.firstCall.args[0].should.eql(toolName);94            execStub.calledTwice.should.be.true;95            execStub.firstCall.args[0].should.eql(toolName);96            execStub.firstCall.args[1].should.eql(['-u', udid, tiffPath]);97            execStub.secondCall.args[0].should.eql('sips');98            execStub.secondCall.args[1].should.eql(99              ['-r', '-90', '-s', 'format', 'png', tiffPath, '--out', pngPath]);100            fsRimRafStub.callCount.should.eql(4);101            fsReadFileStub.calledOnce.should.be.true;102            fsReadFileStub.firstCall.args[0].should.eql(pngPath);103            pathStub.calledTwice.should.be.true;104          });105          it('should use idevicescreenshot if WDA fails', async function () {106            proxyStub.onFirstCall().returns(null);107            proxyStub.onSecondCall().returns('LANDSCAPE');108            (await driver.getScreenshot()).should.eql(pngFileContent.toString('base64'));109            proxyStub.callCount.should.eql(2);110            proxyStub.firstCall.args.should.eql(['/screenshot', 'GET']);111            proxyStub.secondCall.args.should.eql(['/orientation', 'GET']);112          });113          it('should use idevicescreenshot if specified in realDeviceScreenshotter cap', async function () {114            proxyStub.onFirstCall().returns('LANDSCAPE');115            driver.opts.realDeviceScreenshotter = 'idevicescreenshot';116            (await driver.getScreenshot()).should.eql(pngFileContent.toString('base64'));117            proxyStub.callCount.should.eql(1);118          });119        });120        describe('failure', function () {121          beforeEach(function () {122            proxyStub.onFirstCall().returns(null);123            fsWhichStub = sinon.stub(fs, 'which');124            fsWhichStub.throws(new Error('No program found'));125          });126          afterEach(function () {127            fsWhichStub.calledOnce.should.be.true;128            fsWhichStub.firstCall.args[0].should.eql(toolName);129          });130          it('should throw an error if idevicescreenshot is not available and realDeviceScreenshotter set', async function () {131            driver.opts.realDeviceScreenshotter = 'idevicescreenshot';132            await driver.getScreenshot().should.eventually.be.rejectedWith(/No 'idevicescreenshot' program found/);133          });134        });135      });136    });137  });...test.url.js
Source:test.url.js  
...112                if(doScreenshot && !/^(closeWindow):/.test(title)){113                    var filepath = screenshotPath + '/' + caseName.replace(/[^\/]+$/, function(all){114                        return all.replace(/\s*[:\.\:\-\s]\s*/g, '_');115                    }) + '_' + (stepId++) + '.png';116                    return _this.driver.getScreenshot(filepath).catch(function(){});117                }118            });119            after(function(){120                return this.driver.close();121            });122        });123    });124}125function getRootPath(){126    var rootPath = path.resolve(__dirname);127    while(rootPath){128        if(fs.existsSync(rootPath + '/config.json')){129            break;130        }...jwebdriver-mobile.js
Source:jwebdriver-mobile.js  
...81            afterEach(async function(){82                let self = this;83                let filepath = self.screenshotPath + '/' + self.caseName + '_' + self.stepId;84                let driver = self.driver;85                await driver.getScreenshot(filepath + '.png');86                let json = await driver.source();87                fs.writeFileSync(filepath + '.json', json);88            });89            after(function(){90                return this.driver.close();91            });92        });93    });94}95function getRootPath(){96    let rootPath = path.resolve(__dirname);97    while(rootPath){98        if(fs.existsSync(rootPath + '/config.json')){99            break;...actions-e2e-specs.js
Source:actions-e2e-specs.js  
...49    });50  });51  describe('getScreenshot', function () {52    it('should return valid base64-encoded screenshot', async function () {53      const base64screenshot = await driver.getScreenshot();54      const imageMagic = Buffer.from(base64screenshot, 'base64').toString('hex', 0, PNG_MAGIC_LENGTH);55      imageMagic.should.be.equal(PNG_MAGIC);56    });57  });...screenshot-specs.js
Source:screenshot-specs.js  
...4describe('testapp - screenshots', function () {5  describe('default', function () {6    const driver = setup(this, desired).driver;7    it('should get an app screenshot', async function () {8      (await driver.getScreenshot()).should.exist;9    });10    // TODO: fails in ci env, investigate11    it('should get an app screenshot in landscape mode @skip-ci', async function () {12      let screenshot1 = (await driver.getScreenshot());13      screenshot1.should.exist;14      try {15        await driver.setOrientation('LANDSCAPE');16      } catch (e) {17        // A useless error does often exist here, let's ignore it18      }19      let screenshot2 = await driver.getScreenshot();20      screenshot2.should.exist;21      screenshot2.should.not.eql(screenshot1);22      // cooldown23      await B.delay(3000);24    });25  });26  describe('setting screenshotWaitTimeout', function () {27    const driver = setup(this, desired).driver;28    it('should get an app screenshot', async function () {29      (await driver.getScreenshot()).should.exist;30    });31  });...viewport-screenshot-specs.js
Source:viewport-screenshot-specs.js  
...15    sinon.stub(driver, 'getWindowSize').returns({width: 320, height: 568});16    sinon.stub(driver, 'getDevicePixelRatio').returns(2);17    sinon.stub(driver, 'getStatusBarHeight').returns(0);18    sinon.stub(driver, 'getScreenshot').returns(await getImage('screenshot.b64'));19    let screenshot = await driver.getScreenshot();20    expect(screenshot).to.be.not.empty;21  });...Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    driver = new webdriver.Builder()3    .forBrowser('chrome')4    .build();5driver.findElement(By.name('q')).sendKeys('webdriver');6driver.findElement(By.name('btnG')).click();7driver.wait(until.titleIs('webdriver - Google Search'), 1000);8driver.getScreenshot().then(function(image, err) {9    require('fs').writeFile('out.png', image, 'base64', function(err) {10        console.log(err);11    });12});13driver.quit();14var capabilities = {15};16var capabilities = {17};Using AI Code Generation
1var webdriver = require('selenium-webdriver');2}).build();3driver.getScreenshot().then(function(screenShot) {4});5driver.quit();6var webdriver = require('selenium-webdriver');7}).build();8driver.getScreenshot().then(function(screenShot) {9});10driver.quit();11var webdriver = require('selenium-webdriver');12}).build();13driver.getScreenshot().then(function(screenShot) {14});15driver.quit();16var webdriver = require('selenium-webdriver');Using AI Code Generation
1driver.getScreenshot().then(function (image, err) {2    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {3        console.log(err);4    });5});6driver.getScreenshot().then(function (image, err) {7    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {8        console.log(err);9    });10});11driver.getScreenshot().then(function (image, err) {12    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {13        console.log(err);14    });15});16driver.getScreenshot().then(function (image, err) {17    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {18        console.log(err);19    });20});21driver.getScreenshot().then(function (image, err) {22    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {23        console.log(err);24    });25});26driver.getScreenshot().then(function (image, err) {27    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {28        console.log(err);29    });30});31driver.getScreenshot().then(function (image, err) {32    require('fs').writeFile('screenshot.png', image, 'base64', function (err) {33        console.log(err);34    });35});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.getScreenshot().then(function(data){10    fs.writeFile('screenshot.png', data, 'base64', function(err) {11        console.log(err);12    });13});14driver.quit();15{16  "scripts": {17  },18  "dependencies": {19  }20}Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3  desiredCapabilities: {4  }5};6var client = webdriverio.remote(options);7  .init()8  .click('~buttonTestCD')9  .pause(1000)10  .click('~buttonTest')11  .pause(1000)12  .click('~buttonTestCD')13  .pause(1000)14  .click('~buttonTest')15  .pause(1000)16  .click('~buttonTestCD')17  .pause(1000)18  .click('~buttonTest')19  .pause(1000)20  .click('~buttonTestCD')21  .pause(1000)22  .click('~buttonTest')23  .pause(1000)24  .end();25client.getScreenshot().then(function (image) {26  require('fs').writeFileSync('screen.png', image, 'base64');27});Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3    .forBrowser('chrome')4    .build();5driver.getScreenshot().then(function(data) {6    require('fs').writeFile('out.png', data, 'base64', function(err) {7        console.log(err);8    });9});10driver.quit();Using AI Code Generation
1var wd = require('wd');2var fs = require('fs');3var path = require('path');4var driver = wd.promiseChainRemote('localhost', 4723);5driver.configureHttp({6});7    .init({Using AI Code Generation
1var wd = require('wd');2var fs = require('fs');3var driver = wd.promiseChainRemote('localhost', 4723);4driver.init({5}).then(function() {6  return driver.getScreenshot();7}).then(function(screenshot) {8  var stream = fs.createWriteStream("my_screenshot.png");9  stream.write(new Buffer(screenshot, 'base64'));10  stream.end();11});Using AI Code Generation
1var driver = require("appium-android-driver");2var fs = require("fs");3driver.getScreenshot().then(function(screenshot){4fs.writeFile("screenshot.png", screenshot, 'base64', function(err){5if(err){6console.log(err);7}8else{9console.log("screenshot saved");10}11});12});13var driver = require("appium-android-driver");14var fs = require("fs");15driver.getPageSource().then(function(pageSource){16fs.writeFile("pageSource.txt", pageSource, function(err){17if(err){18console.log(err);19}20else{21console.log("page source saved");22}23});24});25var driver = require("appium-android-driver");26driver.getOrientation().then(function(orientation){27console.log("orientation is: " + orientation);28});29var driver = require("appium-android-driver");30driver.setOrientation("landscape").then(function(){31console.log("orientation set");32});33var driver = require("appium-android-driver");34driver.getGeoLocation().then(function(location){35console.log("location is: " + location);36});37var driver = require("appium-android-driver");38driver.setGeoLocation({latitude: 56Learn 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!!
