Best JavaScript code snippet using appium-xcuitest-driver
element-specs.js
Source:element-specs.js  
...189  describe('getLocation', () => {190    it('should get location of an element', async () => {191      driver.bootstrap.sendAction192        .withArgs('element:getLocation').returns('loc_info');193      await driver.getLocation('el1').should.become('loc_info');194      driver.bootstrap.sendAction195        .calledWithExactly('element:getLocation', {elementId: 'el1'})196        .should.be.true;197    });198  });199  describe('getLocationInView', () => {200    it('should get location of an element', async () => {201      sandbox.stub(driver, 'getLocation');202      driver.getLocation.returns('loc_info');203      await driver.getLocationInView('el1').should.become('loc_info');204      driver.getLocation.calledWithExactly('el1').should.be.true;205    });206  });207  describe('getSize', () => {...image-element-specs.js
Source:image-element-specs.js  
1import _ from 'lodash';2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';4import BaseDriver, { ImageElement } from '../..';5import { makeImageElementCache, getImgElFromArgs } from '../../lib/basedriver/image-element';6import { IMAGE_ELEMENT_PREFIX } from '../../lib/constants';7import sinon from 'sinon';8chai.should();9chai.use(chaiAsPromised);10const defRect = {x: 100, y: 110, width: 50, height: 25};11const defTemplate = 'iVBORasdf';12describe('ImageElement', function () {13  const driver = new BaseDriver();14  describe('.size', function () {15    it('should return the width and height of the image el', function () {16      const el = new ImageElement(defTemplate, defRect);17      el.size.should.eql({width: defRect.width, height: defRect.height});18    });19  });20  describe('.location', function () {21    it('should return the location of the image el', function () {22      const el = new ImageElement(defTemplate, defRect);23      el.location.should.eql({x: defRect.x, y: defRect.y});24    });25  });26  describe('.center', function () {27    it('should return the center location of the image el', function () {28      const el = new ImageElement(defTemplate, defRect);29      el.center.should.eql({30        x: defRect.x + defRect.width / 2,31        y: defRect.y + defRect.height / 232      });33    });34  });35  describe('.asElement', function () {36    it('should get the webdriver object representation of the element', function () {37      const el = new ImageElement(defTemplate, defRect);38      el.asElement('ELEMENT').ELEMENT.should.match(/^appium-image-el/);39    });40  });41  describe('.equals', function () {42    it('should say two image elements with same rect are equal', function () {43      const el1 = new ImageElement('foo', defRect);44      const el2 = new ImageElement('bar', defRect);45      el1.equals(el2).should.be.true;46      el2.equals(el1).should.be.true;47    });48    it('should say two image elements with different rect are not equal', function () {49      const el1 = new ImageElement(defTemplate, {...defRect, x: 0});50      const el2 = new ImageElement(defTemplate, defRect);51      el1.equals(el2).should.be.false;52      el2.equals(el1).should.be.false;53    });54  });55  describe('.click', function () {56    it('should reject an invalid tap strategy', async function () {57      const d = new BaseDriver();58      const el = new ImageElement(defTemplate, defRect);59      await d.settings.update({imageElementTapStrategy: 'bad'});60      await el.click(d).should.eventually.be.rejectedWith(/Incorrect imageElementTapStrategy/);61    });62    it('should try to check for image element staleness, and throw if stale', async function () {63      const d = new BaseDriver();64      sinon.stub(d, 'findByImage').throws();65      const el = new ImageElement(defTemplate, defRect);66      // we need to check for staleness if explicitly requested to do so67      await d.settings.update({68        checkForImageElementStaleness: true,69        autoUpdateImageElementPosition: false70      });71      await el.click(d).should.eventually.be.rejectedWith(/no longer attached/);72      // and also if we are updating the element position73      await d.settings.update({74        checkForImageElementStaleness: false,75        autoUpdateImageElementPosition: true76      });77      await el.click(d).should.eventually.be.rejectedWith(/no longer attached/);78    });79    it('should auto-update element position if requested', async function () {80      const d = new BaseDriver();81      d.performActions = _.noop;82      sinon.stub(d, 'performActions');83      const el = new ImageElement(defTemplate, defRect);84      const newRect = {...defRect, x: defRect.x + 10, y: defRect.y + 5};85      const elPos2 = new ImageElement(defTemplate, newRect);86      sinon.stub(d, 'findByImage').returns(elPos2);87      await d.settings.update({88        autoUpdateImageElementPosition: true,89      });90      el.rect.should.not.eql(newRect);91      await el.click(d);92      el.rect.should.eql(newRect);93    });94    it('should tap the center of an element using w3c actions by default', async function () {95      const d = new BaseDriver();96      d.performActions = _.noop;97      const actionStub = sinon.stub(d, 'performActions');98      const el = new ImageElement(defTemplate, defRect);99      // skip the staleness check for this test100      await d.settings.update({101        checkForImageElementStaleness: false,102      });103      await el.click(d);104      const pointerMoveAction = actionStub.args[0][0][0].actions[0];105      pointerMoveAction.x.should.equal(el.center.x);106      pointerMoveAction.y.should.equal(el.center.y);107    });108    it('should fall back to touchactions if w3c actions do not exist on driver', async function () {109      const d = new BaseDriver();110      d.performTouch = _.noop;111      const actionStub = sinon.stub(d, 'performTouch');112      const el = new ImageElement(defTemplate, defRect);113      // skip the staleness check for this test114      await d.settings.update({115        checkForImageElementStaleness: false,116      });117      await el.click(d);118      const action = actionStub.args[0][0][0].options;119      action.x.should.equal(el.center.x);120      action.y.should.equal(el.center.y);121    });122    it('should use touchactions if requested', async function () {123      const d = new BaseDriver();124      d.performActions = _.noop;125      const w3cStub = sinon.stub(d, 'performActions');126      d.performTouch = _.noop;127      const touchStub = sinon.stub(d, 'performTouch');128      const el = new ImageElement(defTemplate, defRect);129      // skip the staleness check for this test130      await d.settings.update({131        checkForImageElementStaleness: false,132        imageElementTapStrategy: 'touchActions',133      });134      await el.click(d);135      const action = touchStub.args[0][0][0].options;136      action.x.should.equal(el.center.x);137      action.y.should.equal(el.center.y);138      w3cStub.callCount.should.eql(0);139    });140    it('should throw if driver does not implement any type of action', async function () {141      const d = new BaseDriver();142      const el = new ImageElement(defTemplate, defRect);143      // skip the staleness check for this test144      await d.settings.update({145        checkForImageElementStaleness: false,146      });147      await el.click(d).should.eventually.be.rejectedWith(/did not implement/);148    });149  });150  describe('#execute', function () {151    // aGFwcHkgdGVzdGluZw== is 'happy testing'152    const imgEl = new ImageElement(defTemplate, defRect, 0, 'aGFwcHkgdGVzdGluZw==');153    const clickStub = sinon.stub(imgEl, 'click');154    before(function () {155      driver._imgElCache.set(imgEl.id, imgEl);156      clickStub.returns(true);157    });158    after(function () {159      driver._imgElCache.reset();160      clickStub.restore();161    });162    it('should reject executions on elements not in the cache', async function () {163      await ImageElement.execute(driver, 'click', 'appium-image-element-foo')164        .should.eventually.be.rejectedWith(/element could not be located/);165    });166    it('should reject executions for unsupported commands', async function () {167      await ImageElement.execute(driver, 'foobar', imgEl.id)168        .should.eventually.be.rejectedWith(/not yet been implemented/);169    });170    it('should get displayed status of element', async function () {171      await ImageElement.execute(driver, 'elementDisplayed', imgEl.id)172        .should.eventually.be.true;173    });174    it('should get size of element', async function () {175      await ImageElement.execute(driver, 'getSize', imgEl.id)176        .should.eventually.eql({width: defRect.width, height: defRect.height});177    });178    it('should get location of element', async function () {179      await ImageElement.execute(driver, 'getLocation', imgEl.id)180        .should.eventually.eql({x: defRect.x, y: defRect.y});181    });182    it('should get location in view of element', async function () {183      await ImageElement.execute(driver, 'getLocation', imgEl.id)184        .should.eventually.eql({x: defRect.x, y: defRect.y});185    });186    it('should get rect of element', async function () {187      await ImageElement.execute(driver, 'getElementRect', imgEl.id)188        .should.eventually.eql(defRect);189    });190    it('should get score of element', async function () {191      await ImageElement.execute(driver, 'getAttribute', imgEl.id, 'score')192        .should.eventually.eql(0);193    });194    it('should get visual of element', async function () {195      await ImageElement.execute(driver, 'getAttribute', imgEl.id, 'visual')196        .should.eventually.eql('aGFwcHkgdGVzdGluZw==');197    });198    it('should get null as visual of element by default', async function () {199      const imgElement = new ImageElement(defTemplate, defRect);200      driver._imgElCache.set(imgElement.id, imgElement);201      await ImageElement.execute(driver, 'getAttribute', imgElement.id, 'visual')202        .should.eventually.eql(null);203    });204    it('should not get other attribute', async function () {205      await ImageElement.execute(driver, 'getAttribute', imgEl.id, 'content-desc')206        .should.eventually.rejectedWith('Method has not yet been implemented');207    });208    it('should click element', async function () {209      await ImageElement.execute(driver, 'click', imgEl.id)210        .should.eventually.be.true;211    });212  });213});214describe('image element LRU cache', function () {215  it('should accept and cache image elements', function () {216    const el1 = new ImageElement(defTemplate, defRect);217    const el2 = new ImageElement(defTemplate, defRect);218    const cache = makeImageElementCache();219    cache.set(el1.id, el1);220    el1.equals(cache.get(el1.id)).should.be.true;221    _.isUndefined(cache.get(el2.id)).should.be.true;222    cache.has(el1.id).should.be.true;223    cache.has(el2.id).should.be.false;224  });225  it('once cache reaches max size, should eject image elements', function () {226    const el1 = new ImageElement(defTemplate, defRect);227    const el2 = new ImageElement(defTemplate, defRect);228    const cache = makeImageElementCache(defTemplate.length + 1);229    cache.set(el1.id, el1);230    cache.has(el1.id).should.be.true;231    cache.set(el2.id, el2);232    cache.has(el2.id).should.be.true;233    cache.has(el1.id).should.be.false;234  });235});236describe('getImgElFromArgs', function () {237  it('should return the image element id from json obj in args', function () {238    const imgEl = `${IMAGE_ELEMENT_PREFIX}foo`;239    const args = [1, 'foo', imgEl];240    getImgElFromArgs(args).should.eql(imgEl);241  });242  it('should not return anything if image element id not in args', function () {243    const args = [1, 'foo'];244    _.isUndefined(getImgElFromArgs(args)).should.be.true;245  });246  it('should not find image element id in anything but prefix', function () {247    const notImgEl = `foo${IMAGE_ELEMENT_PREFIX}`;248    const args = [1, 'foo', notImgEl];249    _.isUndefined(getImgElFromArgs(args)).should.be.true;250  });...index.js
Source:index.js  
...70   *71   * @returns {String}72   */73  getLocation() {74    const location = this.driver.getLocation();75    this.log('getLocation', location);76    return location;77  }78  /**79   * Set the learner's current location80   *81   * @param {string} location82   * @returns {boolean} success83   */84  setLocation(location) {85    if (typeof location !== 'string') {86      this.log('setLocation: Invalid data type given. Expected string.', location);87      return false;88    }...SettingMap.js
Source:SettingMap.js  
1let jsonobj;2let foo = function () {3    var map = new ol.Map({4        target: 'map',5        layers: [6            new ol.layer.Tile({7                source: new ol.source.OSM()8            })9        ],10        view: new ol.View({11            center: ol.proj.fromLonLat([19.8424, 45.2541]),12            zoom: 1513        })14    });15    map.on('click', function (evt) {16        var coord = ol.proj.toLonLat(evt.coordinate);17        alert(coord);18        reverseGeocode(coord);19    });20}21let foof1 = function () {22    $("#divwriteuserdata").append(`<table class="table table - bordered" style="float:right;width:40%;height:50%">23        <thead>24        <tr class="success">25            <th colspan="2">26                Location details preview27            </th>28        </tr>29        </thead>30        <tbody>31        <tr>32            <td>Your current address:</td>33            <td>34                <input type="text" id="txtAddress"/>35            </td>36        </tr>37        <tr>38            <td>Coordinates:</td>39            <td>40                <input type="text" id="txtX"/>41                <input type="text" id="txtY"/>42            </td>43        </tr>44        <tr class="success">45                <td colspan="2">46                    <input id="btnSaveLoc" class="btn btn-primary" type="button" value="Save location"/>47                </td>48            </tr>49        </tbody>50    </table >`);51    $("#btnSaveLoc").click(function () {52        $.post("/api/Driver/SetLocation/", { json: jsonobj }, function () { location.href = `Driver.html`; })53            .fail(function () {54                alert(`error while sending address`);55            });56    });57    $("#btnSubmitLoc").click(function () {58        alert(jsonobj);59        $.post("/api/Driver/GetLocation/", { json: jsonobj }, function (location) {60            $("#txtAddress").val(location.Address.Street + location.Address.HomeNumber);61            $("#txtX").val(location.X);62            $("#txtY").val(location.Y);63        })64            .fail(function () {65                alert(`error while sending location`);66            });67    });68}69let ShowMap = function (placeForMap) {70    $(placeForMap).html(`<h2>Location</h2>71    <button class="btn btn-primary" id="btnSubmitLoc">Submit location</button>72    <div id="map" class="map" style="float:left;width:60%;height:50%;"></div>73    `);74    foo();75};76function addMarker(lon, lat, icon) {77    var iconFeatures = [];78    var iconGeometry = new ol.geom.Point(ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'));79    var iconFeature = new ol.Feature({80        geometry: iconGeometry81    });82    iconFeatures.push(iconFeature);83    var vectorSource = new ol.source.Vector({84        features: iconFeatures //add an array of features85    });86    var iconStyle = new ol.style.Style({87        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({88            anchor: [0.5, 46],89            anchorXUnits: 'fraction',90            anchorYUnits: 'pixels',91            opacity: 0.95,92            src: icon93        }))94    });95    var vectorLayer = new ol.layer.Vector({96        source: vectorSource,97        style: iconStyle98    });99    map.addLayer(vectorLayer);100    return iconFeature;101}102function reverseGeocode(coords) {103    fetch('https://nominatim.openstreetmap.org/reverse?format=json&lon=' + coords[0] + '&lat=' + coords[1])104        .then(function (response) {105            return response.json();106        }).then(function (json) {107            console.log(json);108            jsonobj = json;109        });...location-specs.js
Source:location-specs.js  
...8  let session = setup(this, desired);9  let driver = session.driver;10  it('should return the right x/y coordinates for getLocation', async function () {11    let el = await driver.findElement('class name', 'UIAButton');12    let loc = await driver.getLocation(el);13    [94, 110].should.contain(parseInt(loc.x, 10));14    loc.y.should.be.above(120);15  });16  it('should return the right x/y coordinates for getLocationInView', async function () {17    let el = await driver.findElement('class name', 'UIAButton');18    let loc = await driver.getLocation(el);19    [94, 110].should.contain(parseInt(loc.x, 10));20    loc.y.should.be.above(120);21  });22  it('should not error with valid lat/lon and no options', async function () {23    await driver.setGeoLocation({latitude: -30, longitude: 30});24  });25  it('should error with invalid lat/lon and no options', async function () {26    await B.resolve(driver.setGeoLocation({latitude: -150, longitude: 30}))27      .catch(throwMatchableError)28      .should.be.rejectedWith(/jsonwpCode: 17 latitude/);29  });30});31describe('testapp - location - 2 @skip-ci', function () {32  let session = setup(this, _.defaults(...attribute-e2e-specs.js
Source:attribute-e2e-specs.js  
...41  it('should be able to find displayed attribute through normal func', async () => {42    await driver.elementDisplayed(animationEl).should.eventually.become(true);43  });44  it('should be able to get element location using getLocation', async () => {45    let location = await driver.getLocation(animationEl);46    location.x.should.be.at.least(0);47    location.y.should.be.at.least(0);48  });49  it('should be able to get element location using getLocationInView', async () => {50    let location = await driver.getLocationInView(animationEl);51    location.x.should.be.at.least(0);52    location.y.should.be.at.least(0);53  });54  it('should be able to get element size', async () => {55    let size = await driver.getSize(animationEl);56    size.width.should.be.at.least(0);57    size.height.should.be.at.least(0);58  });59});driver.controller.js
Source:driver.controller.js  
1import Driver from './driver.model';2import helper from '../helper';3const registerDriver = async (req, res) => {4  const { name, vehicle } = req.body;5  if (!name || !vehicle) return res.status(400).send({ message: 'Invalid fields.' });6  Driver.findOne({ name }, (err, driver) => {7    if (err) return res.status(400).send(err);8    else if (driver) return res.status(400).send({ message: 'Driver already registered.' });9    const newDriver = new Driver({ name, vehicle });10    newDriver.save(err => {11      if (err) return res.status(400).send(err);12      return res.status(200).send({ message: 'Driver has been registered.' });13    });14  });15}16const getLocation = async (req, res) => {17  const { id } = req.body;18  if (!id) return res.status(400).send({ message: 'Invalid fields.' });19  Driver.findById(id, (err, driver) => {20    if (err || driver == null) return res.status(400).send({ message: 'Unregistered driver.' });21    if (!driver.isAvailable) return res.status(400).send({ message: 'Offline driver.' });22    return res.status(200).json(driver.location);23  });24}25const setLocation = async (req, res) => {26  const { id, lat, lng } = req.body;27  if (!id || !lat || !lng) return res.status(400).send({ message: 'Invalid fields.' });28  Driver.findById(id, (err, driver) => {29    if (err || driver == null) return res.status(400).send({ message: 'Unregistered driver.' });30    driver.location.lat = parseFloat(lat, 10);31    driver.location.lng = parseFloat(lng, 10);32    driver.isAvailable = true;33    driver.save(err => {34      if (err) return res.status(400).send(err);35      return res.status(200).json(driver.location);36    });37  });38}39const getModelTypes = async (req, res) => {40  const driverTypes = await helper.getModelTypes(Driver);41  res.status(200).json(driverTypes);42}43export default {44  registerDriver,45  getLocation,46  setLocation,47  getModelTypes,...touch-specs.js
Source:touch-specs.js  
...12  }).driver;13  it('should flick element', async function () {14    await driver.setUrl(`${env.TEST_END_POINT}touch.html`);15    let flickElem = await driver.findElement('id', 'flickElem');16    let l1 = await driver.getLocation(flickElem);17    let dx = 30, dy = 30;18    flickElem = await driver.findElement('id', 'flickElem');19    await driver.flick(flickElem, dx, dy, 0);20    await B.delay(1000);21    let l2 = await driver.getLocation(flickElem);22    // UI Atomation's flickFromTo() seems to be not prices enough.23    // And in most cases safari receives the last touchmove event24    // with the coordinates which are by one pixel less than desired25    // destination. Hence allow some deviation here.26    l2.x.should.be.within(l1.x + dx - 2, l1.x + dx + 2);27    l2.y.should.be.within(l1.y + dy - 2, l1.y + dy + 2);28  });29  it('should not be able to do native touch actions', async function () {30    let el = await driver.findElement('id', 'comments');31    let gestures = [32      {action: 'press', options: {element: el}},33      {action: 'release'}34    ];35    await driver.performTouch(gestures).should.eventually.be.rejected;...Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3    desiredCapabilities: {4    }5};6const client = webdriverio.remote(options);7    .init()8    .getLocation('1')9    .then(function (res) {10        console.log(res);11    })12    .end();13const webdriverio = require('webdriverio');14const options = {15    desiredCapabilities: {16    }17};18const client = webdriverio.remote(options);19    .init()20    .getLocationInView('1')21    .then(function (res) {22        console.log(res);23    })24    .end();25const webdriverio = require('webdriverio');26const options = {27    desiredCapabilities: {28    }29};30const client = webdriverio.remote(options);31    .init()32    .getOrientation()33    .then(function (res) {34        console.log(res);35    })36    .end();37const webdriverio = require('webdriverio');38const options = {39    desiredCapabilities: {Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6chai.should();7chaiAsPromised.transferPromiseness = wd.transferPromiseness;8var desired = {9};10var driver = wd.promiseChainRemote('localhost', 4723);11driver.init(desired).then(function () {12    .then(function (location) {13      driver.tap(1, location.x, location.y, 0.1);14    });15});16driver.quit();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!!
