How to use driver.execute method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

gesture-specs.js

Source:gesture-specs.js Github

copy

Full Screen

...82  });83  describe('mobile methods', () => {84    describe('anything other than scroll', () => {85      it('should throw an error', async () => {86        await driver.execute('mobile: somesuch').should.be.rejected;87      });88    });89    describe('scroll', () => {90      it('should throw an error if no scroll type is specified', async () => {91        await driver.execute('mobile: scroll', {element: 4})92          .should.eventually.be.rejectedWith(/Mobile scroll supports the following strategies/);93      });94      it('should pass through bare element', async () => {95        await driver.execute('mobile: scroll', {element: 4, direction: 'down'});96        proxySpy.calledOnce.should.be.true;97        proxySpy.firstCall.args[0].should.eql('/wda/element/4/scroll');98        proxySpy.firstCall.args[1].should.eql('POST');99      });100      it('should unpack element object', async () => {101        await driver.execute('mobile: scroll', {element: {ELEMENT: 4}, direction: 'down'});102        proxySpy.calledOnce.should.be.true;103        proxySpy.firstCall.args[0].should.eql('/wda/element/4/scroll');104        proxySpy.firstCall.args[1].should.eql('POST');105      });106      it('should pass name strategy exclusively', async () => {107        await driver.execute('mobile: scroll', {element: 4, direction: 'down', name: 'something'});108        proxySpy.calledOnce.should.be.true;109        proxySpy.firstCall.args[0].should.eql('/wda/element/4/scroll');110        proxySpy.firstCall.args[1].should.eql('POST');111        proxySpy.firstCall.args[2].should.eql({name: 'something'});112      });113      it('should pass direction strategy exclusively', async () => {114        await driver.execute('mobile: scroll', {element: 4, direction: 'down', predicateString: 'something'});115        proxySpy.calledOnce.should.be.true;116        proxySpy.firstCall.args[0].should.eql('/wda/element/4/scroll');117        proxySpy.firstCall.args[1].should.eql('POST');118        proxySpy.firstCall.args[2].should.eql({direction: 'down'});119      });120      it('should pass predicateString strategy exclusively', async () => {121        await driver.execute('mobile: scroll', {element: 4, toVisible: true, predicateString: 'something'});122        proxySpy.calledOnce.should.be.true;123        proxySpy.firstCall.args[0].should.eql('/wda/element/4/scroll');124        proxySpy.firstCall.args[1].should.eql('POST');125        proxySpy.firstCall.args[2].should.eql({predicateString: 'something'});126      });127    });128    describe('swipe', () => {129      const commandName = 'swipe';130      it('should throw an error if no direction is specified', async () => {131        await driver.execute(`mobile: ${commandName}`, {element: 4})132          .should.be.rejectedWith(/Error: Mobile swipe requires direction/);133      });134      it('should throw an error if invalid direction', async () => {135        await driver.execute(`mobile: ${commandName}`, {element: 4, direction: 'foo'})136          .should.be.rejectedWith(/Error: Direction must be up, down, left or right/);137      });138      it('should proxy a swipe up request through to WDA', async () => {139        await driver.execute(`mobile: ${commandName}`, {element: 4, direction: 'up'});140        proxySpy.calledOnce.should.be.true;141        proxySpy.firstCall.args[0].should.eql('/wda/element/4/swipe');142        proxySpy.firstCall.args[1].should.eql('POST');143        return proxySpy.firstCall.args[2].should.eql({direction: 'up'});144      });145    });146    describe('pinch', () => {147      const commandName = 'pinch';148      it('should throw an error if no mandatory parameter is specified', async () => {149        await driver.execute(`mobile: ${commandName}`, {element: 4, scale: 4.1})150          .should.be.rejectedWith(/parameter is mandatory/);151        await driver.execute(`mobile: ${commandName}`, {element: 4, velocity: -0.5})152          .should.be.rejectedWith(/parameter is mandatory/);153      });154      it('should throw an error if param is invalid', async () => {155        await driver.execute(`mobile: ${commandName}`, {element: 4, scale: '', velocity: 1})156          .should.be.rejectedWith(/should be a valid number/);157        await driver.execute(`mobile: ${commandName}`, {element: 4, scale: 0, velocity: null})158          .should.be.rejectedWith(/should be a valid number/);159      });160      it('should proxy a pinch request through to WDA', async () => {161        await driver.execute(`mobile: ${commandName}`, {element: 4, scale: 1, velocity: '1'});162        proxySpy.calledOnce.should.be.true;163        proxySpy.firstCall.args[0].should.eql('/wda/element/4/pinch');164        proxySpy.firstCall.args[1].should.eql('POST');165        proxySpy.firstCall.args[2].should.have.keys(['scale', 'velocity']);166      });167    });168    describe('doubleTap', () => {169      const commandName = 'doubleTap';170      it('should throw an error if no mandatory parameter is specified', async () => {171        await driver.execute(`mobile: ${commandName}`, {x: 100}).should.be.rejectedWith(/parameter is mandatory/);172        await driver.execute(`mobile: ${commandName}`, {y: 200}).should.be.rejectedWith(/parameter is mandatory/);173      });174      it('should throw an error if param is invalid', async () => {175        await driver.execute(`mobile: ${commandName}`, {x: '', y: 1}).should.be.rejectedWith(/should be a valid number/);176        await driver.execute(`mobile: ${commandName}`, {x: 1, y: null}).should.be.rejectedWith(/should be a valid number/);177      });178      it('should proxy a doubleTap request for an element through to WDA', async () => {179        await driver.execute(`mobile: ${commandName}`, {element: 4});180        proxySpy.calledOnce.should.be.true;181        proxySpy.firstCall.args[0].should.eql('/wda/element/4/doubleTap');182        proxySpy.firstCall.args[1].should.eql('POST');183      });184      it('should proxy a doubleTap request for a coordinate point through to WDA', async () => {185        await driver.execute(`mobile: ${commandName}`, {x: 100, y: 100});186        proxySpy.calledOnce.should.be.true;187        proxySpy.firstCall.args[0].should.eql('/wda/doubleTap');188        proxySpy.firstCall.args[1].should.eql('POST');189        proxySpy.firstCall.args[2].should.have.keys(['x', 'y']);190      });191    });192    describe('twoFingerTap', () => {193      const commandName = 'twoFingerTap';194      it('should proxy a twoFingerTap request for an element through to WDA', async () => {195        await driver.execute(`mobile: ${commandName}`, {element: 4});196        proxySpy.calledOnce.should.be.true;197        proxySpy.firstCall.args[0].should.eql('/wda/element/4/twoFingerTap');198        proxySpy.firstCall.args[1].should.eql('POST');199      });200    });201    describe('touchAndHold', () => {202      const commandName = 'touchAndHold';203      it('should throw an error if no mandatory parameter is specified', async () => {204        await driver.execute(`mobile: ${commandName}`, {duration: 100, x: 1}).should.be.rejectedWith(/parameter is mandatory/);205        await driver.execute(`mobile: ${commandName}`, {duration: 100, y: 200}).should.be.rejectedWith(/parameter is mandatory/);206        await driver.execute(`mobile: ${commandName}`, {x: 100, y: 200}).should.be.rejectedWith(/parameter is mandatory/);207      });208      it('should throw an error if param is invalid', async () => {209        await driver.execute(`mobile: ${commandName}`, {duration: '', x: 1, y: 1}).should.be.rejectedWith(/should be a valid number/);210        await driver.execute(`mobile: ${commandName}`, {duration: 1, x: '', y: 1}).should.be.rejectedWith(/should be a valid number/);211        await driver.execute(`mobile: ${commandName}`, {duration: 1, x: 1, y: null}).should.be.rejectedWith(/should be a valid number/);212      });213      it('should proxy a touchAndHold request for an element through to WDA', async () => {214        await driver.execute(`mobile: ${commandName}`, {element: 4, duration: 100});215        proxySpy.calledOnce.should.be.true;216        proxySpy.firstCall.args[0].should.eql('/wda/element/4/touchAndHold');217        proxySpy.firstCall.args[1].should.eql('POST');218        proxySpy.firstCall.args[2].should.have.keys(['duration']);219      });220      it('should proxy a touchAndHold request for a coordinate point through to WDA', async () => {221        await driver.execute('mobile: touchAndHold', {duration: 100, x: 100, y: 100});222        proxySpy.calledOnce.should.be.true;223        proxySpy.firstCall.args[0].should.eql('/wda/touchAndHold');224        proxySpy.firstCall.args[1].should.eql('POST');225        proxySpy.firstCall.args[2].should.have.keys(['duration', 'x', 'y']);226      });227    });228    describe('tap', () => {229      const commandName = 'tap';230      it('should throw an error if no mandatory parameter is specified', async () => {231        await driver.execute(`mobile: ${commandName}`, {}).should.be.rejectedWith(/parameter is mandatory/);232        await driver.execute(`mobile: ${commandName}`, {x: 100}).should.be.rejectedWith(/parameter is mandatory/);233        await driver.execute(`mobile: ${commandName}`, {y: 200}).should.be.rejectedWith(/parameter is mandatory/);234      });235      it('should throw an error if param is invalid', async () => {236        await driver.execute(`mobile: ${commandName}`, {x: '', y: 1}).should.be.rejectedWith(/should be a valid number/);237        await driver.execute(`mobile: ${commandName}`, {x: 1, y: null}).should.be.rejectedWith(/should be a valid number/);238      });239      it('should proxy a tap request for an element through to WDA', async () => {240        await driver.execute(`mobile: ${commandName}`, {element: 4, x: 100, y: 100});241        proxySpy.calledOnce.should.be.true;242        proxySpy.firstCall.args[0].should.eql('/wda/tap/4');243        proxySpy.firstCall.args[1].should.eql('POST');244        proxySpy.firstCall.args[2].should.have.keys(['x', 'y']);245      });246      it('should proxy a tap request for a coordinate point through to WDA', async () => {247        await driver.execute(`mobile: ${commandName}`, {x: 100, y: 100});248        proxySpy.calledOnce.should.be.true;249        proxySpy.firstCall.args[0].should.eql('/wda/tap/0');250        proxySpy.firstCall.args[1].should.eql('POST');251        proxySpy.firstCall.args[2].should.have.keys(['x', 'y']);252      });253    });254    describe('selectPickerWheelValue', () => {255      const commandName = 'selectPickerWheelValue';256      it('should throw an error if no mandatory parameter is specified', async () => {257        await driver.execute(`mobile: ${commandName}`, {}).should.be.rejectedWith(/Element id is expected to be set/);258        await driver.execute(`mobile: ${commandName}`, {element: 4}).should.be.rejectedWith(/is expected to be equal/);259        await driver.execute(`mobile: ${commandName}`, {order: 'next'}).should.be.rejectedWith(/Element id is expected to be set/);260      });261      it('should throw an error if param is invalid', async () => {262        await driver.execute(`mobile: ${commandName}`, {element: 4, order: 'bla'}).should.be.rejectedWith(/is expected to be equal/);263      });264      it('should proxy a selectPickerWheel request for an element through to WDA', async () => {265        await driver.execute(`mobile: ${commandName}`, {element: 4, order: 'next'});266        proxySpy.calledOnce.should.be.true;267        proxySpy.firstCall.args[0].should.eql('/wda/pickerwheel/4/select');268        proxySpy.firstCall.args[1].should.eql('POST');269        proxySpy.firstCall.args[2].should.have.property('order', 'next');270      });271    });272    describe('dragFromToForDuration', () => {273      const commandName = 'dragFromToForDuration';274      it('should throw an error if no mandatory parameter is specified', async () => {275        await driver.execute(`mobile: ${commandName}`, {fromX: 1, fromY: 1, toX: 100, toY: 100})276          .should.be.rejectedWith(/parameter is mandatory/);277        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromY: 1, toX: 100, toY: 100})278          .should.be.rejectedWith(/parameter is mandatory/);279        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, toX: 100, toY: 100})280          .should.be.rejectedWith(/parameter is mandatory/);281        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: 1, toY: 100})282          .should.be.rejectedWith(/parameter is mandatory/);283        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: 1, toX: 100})284          .should.be.rejectedWith(/parameter is mandatory/);285      });286      it('should throw an error if param is invalid', async () => {287        await driver.execute(`mobile: ${commandName}`, {duration: '', fromX: 1, fromY: 1, toX: 100, toY: 100})288          .should.be.rejectedWith(/should be a valid number/);289        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: '', fromY: 1, toX: 100, toY: 100})290          .should.be.rejectedWith(/should be a valid number/);291        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: null, toX: 100, toY: 100})292          .should.be.rejectedWith(/should be a valid number/);293        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: 1, toX: 'blabla', toY: 100})294          .should.be.rejectedWith(/should be a valid number/);295        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: 1, toX: 100, toY: NaN})296          .should.be.rejectedWith(/should be a valid number/);297      });298      it('should proxy a dragFromToForDuration request for an element through to WDA', async () => {299        await driver.execute(`mobile: ${commandName}`, {element: 4, duration: 100, fromX: 1, fromY: 1, toX: 100, toY: 100});300        proxySpy.calledOnce.should.be.true;301        proxySpy.firstCall.args[0].should.eql('/wda/element/4/dragfromtoforduration');302        proxySpy.firstCall.args[1].should.eql('POST');303        proxySpy.firstCall.args[2].should.have.keys(['duration', 'fromX', 'fromY', 'toX', 'toY']);304      });305      it('should proxy a dragFromToForDuration request for a coordinate point through to WDA', async () => {306        await driver.execute(`mobile: ${commandName}`, {duration: 100, fromX: 1, fromY: 1, toX: 100, toY: 100});307        proxySpy.calledOnce.should.be.true;308        proxySpy.firstCall.args[0].should.eql('/wda/dragfromtoforduration');309        proxySpy.firstCall.args[1].should.eql('POST');310        proxySpy.firstCall.args[2].should.have.keys(['duration', 'fromX', 'fromY', 'toX', 'toY']);311      });312    });313    describe('getCoordinates', () => {314      it('should properly parse coordinates if they are presented as string values', async () => {315        const gesture = {316          action: 'moveTo',317          options: {318            x: '100',319            y: '300'320          }...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1const chai = require('chai');2const chaiHttp = require('chai-http');3const server = require('../app');4const expect = chai.expect;5chai.use(chaiHttp);6const chaiAsPromised = require("chai-as-promised");7chai.use(chaiAsPromised);8const { Builder, By, Key, until, WebDriver } = require('selenium-webdriver'), chrome = require('selenium-webdriver/chrome');9var driver;10let name, origin, destination, price, rating, addBtn, sortPrice, sortRating, flightItems, originFilter, destFilter;11const options = new chrome.Options();12options.addArguments(13    'headless'14);15describe('Phone Directory app \n', function() {16  this.timeout(100000);17  before(function(done) {18      driver = new Builder()19          .forBrowser('chrome')20          .setChromeOptions(options)21          .build();22      driver.get('http://localhost:8000')23          .then(() => {24              done();25          });26  });27  after(function() {28      driver.quit();29  })30  beforeEach(async function() {31      driver.navigate().refresh();32      name = await driver.findElement(By.id("name"));33      mobile = await driver.findElement(By.id("mobile"));34      email = await driver.findElement(By.id("email"));35      price = await driver.findElement(By.id("summaryTable"));36      error = await driver.findElement(By.id("error"));37      submit = await driver.findElement(By.id("submit"));38      nameColumn = await driver.findElement(By.id("nameColumn"));39  })40  it('should show error when input fields are empty', async function() {41    name.sendKeys('');42    mobile.sendKeys('');43    email.sendKeys('');44    await submit.click();45    const hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");46    const displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");47    expect(hasNoItemAdded).to.be.true;48    expect(displayError).to.be.true;49  });50  it('should show error when Invalid Inputs are given', async function() {51    // Invalid Name52    name.sendKeys('12345678');53    mobile.sendKeys('9898989898');54    email.sendKeys('admin@xyzcompany.com');55    await submit.click();56    let hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");57    let displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");58    expect(hasNoItemAdded).to.be.true;59    expect(displayError).to.be.true;60    name.sendKeys('John doe of South california State');61    mobile.sendKeys('9898989898');62    email.sendKeys('admin@xyzcompany.com');63    await submit.click();64    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");65    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");66    expect(hasNoItemAdded).to.be.true;67    expect(displayError).to.be.true;68    // Invalid Mobile69    name.sendKeys('John doe');70    mobile.sendKeys('98989898989');71    email.sendKeys('admin@xyzcompany.com');72    await submit.click();73    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");74    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");75    expect(hasNoItemAdded).to.be.true;76    expect(displayError).to.be.true;77    name.sendKeys('John doe');78    mobile.sendKeys('abcdefghi');79    email.sendKeys('admin@xyz.com');80    await submit.click();81    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");82    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");83    expect(hasNoItemAdded).to.be.true;84    expect(displayError).to.be.true;85    // Invalid Email86    name.sendKeys('John doe');87    mobile.sendKeys('9898989898');88    email.sendKeys('#!_@xyz.com');89    await submit.click();90    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");91    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");92    expect(hasNoItemAdded).to.be.true;93    expect(displayError).to.be.true;94    name.sendKeys('John doe');95    mobile.sendKeys('9898989898');96    email.sendKeys('abc zyx@xyz.com');97    await submit.click();98    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");99    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");100    expect(hasNoItemAdded).to.be.true;101    expect(displayError).to.be.true;102    name.sendKeys('John doe');103    mobile.sendKeys('8989898989');104    email.sendKeys('adminadminadminadminadminadmin87767868765856567fhfhjadminadminadmin@xyzcompany.com');105    await submit.click();106    hasNoItemAdded = await driver.executeScript("return document.querySelectorAll('#summaryTable tbody').length === 1");107    displayError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display !== 'none'");108    expect(hasNoItemAdded).to.be.true;109    expect(displayError).to.be.true;110  });111  it('should add the contact on clicking Add', async function() {112    name.sendKeys('John Doe');113    mobile.sendKeys('9898989898');114    email.sendKeys('admin2@xyzcompany.com');115    await submit.click();116    name.sendKeys('John');117    mobile.sendKeys('8989898989');118    email.sendKeys('admin3@xyzcompany.com');119    await submit.click();120    const tbody = "document.querySelectorAll('#summaryTable tbody')[0]";121    const hasItemAdded = await driver.executeScript(`return ${tbody}.childElementCount === 3 &&122      ${tbody}.children[0].children[0].innerText === "Admin" && ${tbody}.children[0].children[1].innerText === "9999999999" && ${tbody}.children[0].children[2].innerText === "admin@xyzcompany.com" &&123      ${tbody}.children[1].children[0].innerText === "John Doe" && ${tbody}.children[1].children[1].innerText === "9898989898" && ${tbody}.children[1].children[2].innerText === "admin2@xyzcompany.com" &&124      ${tbody}.children[2].children[0].innerText === "John" && ${tbody}.children[2].children[1].innerText === "8989898989" && ${tbody}.children[2].children[2].innerText === "admin3@xyzcompany.com"`);125    const noError = await driver.executeScript("return getComputedStyle(document.getElementsByClassName('error')[0]).display === 'none'");126    expect(hasItemAdded).to.be.true;127    expect(noError).to.be.true;128  });129  it('should reset after adding a contact', async function() {130    name.sendKeys('John Doe');131    mobile.sendKeys('9898989898');132    email.sendKeys('admin@xyzcompany.com');133    await submit.click();134    let messageDisplay = await name.getAttribute('value');135    expect(messageDisplay).to.equal('');136    messageDisplay = await email.getAttribute('value');137    expect(messageDisplay).to.equal('');138    messageDisplay = await mobile.getAttribute('value');139    expect(messageDisplay).to.equal('');140  });141  142  it('should allow sort by Contact Name Ascending', async function() {143    name.sendKeys('John Doe');144    mobile.sendKeys('9898989898');145    email.sendKeys('admin@xyzcompany.com');146    await submit.click();147    name.sendKeys('Xavier');148    mobile.sendKeys('9898989898');149    email.sendKeys('admin@xyzcompany.com');150    await submit.click();151    // Ascending152    await nameColumn.click();153    let name1 = "document.querySelectorAll('#summaryTable tbody')[0].children[0].children[0].innerText.toLowerCase()";154    let name2 = "document.querySelectorAll('#summaryTable tbody')[0].children[1].children[0].innerText.toLowerCase()";155    let name3 = "document.querySelectorAll('#summaryTable tbody')[0].children[2].children[0].innerText.toLowerCase()";156    let sorted = await driver.executeScript(`return (${name1} < ${name2}) && (${name1} < ${name3}) && (${name2} < ${name3})`);157    expect(sorted).to.be.true;158    driver.takeScreenshot().then(159      function(image, err) {160        require('fs').writeFile('name-sorting-ascending.png', image, 'base64', function(err) {});161      }162    );163  });164  it('should allow sort by Contact Name Descending', async function() {165    name.sendKeys('John Doe');166    mobile.sendKeys('9898989898');167    email.sendKeys('admin@xyzcompany.com');168    await submit.click();169    name.sendKeys('Xavier');170    mobile.sendKeys('9898989898');171    email.sendKeys('admin@xyzcompany.com');172    await submit.click();173    // Ascending174    await nameColumn.click();175    await nameColumn.click();176    name1 = "document.querySelectorAll('#summaryTable tbody')[0].children[1].children[0].innerText.toLowerCase()";177    name2 = "document.querySelectorAll('#summaryTable tbody')[0].children[2].children[0].innerText.toLowerCase()";178    name3 = "document.querySelectorAll('#summaryTable tbody')[0].children[3].children[0].innerText.toLowerCase()";179    sorted = await driver.executeScript(`return !(${name1} < ${name2}) || (${name1} < ${name3}) || (${name2} < ${name3})`);180    expect(sorted).to.be.true;181  });182  it('should show #f2f2f2 in alternate rows', async function() {183    name.sendKeys('John Doe');184    mobile.sendKeys('9898989898');185    email.sendKeys('admin@xyzcompany.com');186    await submit.click();187    name.sendKeys('Xavier');188    mobile.sendKeys('9898989898');189    email.sendKeys('admin4@xyzcompany.com');190    await submit.click();191    name.sendKeys('Xavier calvin');192    mobile.sendKeys('9898984898');193    email.sendKeys('admin5@xyzcompany.com');194    await submit.click();195    const hasBg = await driver.executeScript("return  getComputedStyle(document.querySelectorAll('#summaryTable tbody')[0].children[0]).background.includes('rgb(242, 242, 242)') && getComputedStyle(document.querySelectorAll('#summaryTable tbody')[0].children[2]).background.includes('rgb(242, 242, 242)')");196    expect(hasBg).to.be.true;197  });...

Full Screen

Full Screen

StorageEngineGears.js

Source:StorageEngineGears.js Github

copy

Full Screen

...40			// create the database41			_driver = google.gears.factory.create(StorageEngineGears.GEARS);42      // the replace regex fixes http://yuilibrary.com/projects/yui2/ticket/2529411, all ascii characters are allowede except / : * ? " < > | ; ,43			_driver.open(window.location.host.replace(/[\/\:\*\?"\<\>\|;,]/g, '') + '-' + StorageEngineGears.DATABASE);44			_driver.execute('CREATE TABLE IF NOT EXISTS ' + TABLE_NAME + ' (key TEXT, location TEXT, value TEXT)');45		}46		isSessionStorage = Util.StorageManager.LOCATION_SESSION === that._location;47		sessionKey = Util.Cookie.get('sessionKey' + StorageEngineGears.ENGINE_NAME);48		if (! sessionKey) {49			_driver.execute('BEGIN');50			_driver.execute('DELETE FROM ' + TABLE_NAME + ' WHERE location="' + eURI(Util.StorageManager.LOCATION_SESSION) + '"');51			_driver.execute('COMMIT');52		}53		rs = _driver.execute('SELECT key FROM ' + TABLE_NAME + ' WHERE location="' + eURI(that._location) + '"');54		keyMap = {};55	56		try {57			// iterate on the rows and map the keys58			while (rs.isValidRow()) {59				var fld = dURI(rs.field(0));60				if (! keyMap[fld]) {61					keyMap[fld] = true;62					that._addKey(fld);63				}64				rs.next();65			}66		} finally {67			rs.close();68		}69		// this is session storage, ensure that the session key is set70		if (isSessionStorage) {71			Util.Cookie.set('sessionKey' + StorageEngineGears.ENGINE_NAME, true);72		}73        that.fireEvent(Util.Storage.CE_READY);74	};75	Lang.extend(StorageEngineGears, Util.StorageEngineKeyed, {76		/*77		 * Implementation to clear the values from the storage engine.78		 * @see YAHOO.util.Storage._clear79		 */80		_clear: function() {81			StorageEngineGears.superclass._clear.call(this);82			_driver.execute('BEGIN');83			_driver.execute('DELETE FROM ' + TABLE_NAME + ' WHERE location="' + eURI(this._location) + '"');84			_driver.execute('COMMIT');85		},86		/*87		 * Implementation to fetch an item from the storage engine.88		 * @see YAHOO.util.Storage._getItem89		 */90		_getItem: function(sKey) {91			var rs = _driver.execute('SELECT value FROM ' + TABLE_NAME + ' WHERE key="' + eURI(sKey) + '" AND location="' + eURI(this._location) + '"'),92				value = '';93			try {94				while (rs.isValidRow()) {95					value += rs.field(0);96					rs.next();97				}98			} finally {99				rs.close();100			}101			return value ? dURI(value) : null;102		},103		/*104		 * Implementation to remove an item from the storage engine.105		 * @see YAHOO.util.Storage._removeItem106		 */107		_removeItem: function(sKey) {108			YAHOO.log("removing gears key: " + sKey);109			StorageEngineGears.superclass._removeItem.call(this, sKey);110			_driver.execute('BEGIN');111			_driver.execute('DELETE FROM ' + TABLE_NAME + ' WHERE key="' + eURI(sKey) + '" AND location="' + eURI(this._location) + '"');112			_driver.execute('COMMIT');113		},114		/*115		 * Implementation to remove an item from the storage engine.116		 * @see YAHOO.util.Storage._setItem117		 */118		_setItem: function(sKey, oData) {119			YAHOO.log("SETTING " + oData + " to " + sKey);120			this._addKey(sKey);121			var sEscapedKey = eURI(sKey),122				sEscapedLocation = eURI(this._location),123				sEscapedValue = eURI(oData), // escaped twice, maybe not necessary124				aValues = [],125				nLen = SQL_STMT_LIMIT - (sEscapedKey + sEscapedLocation).length,126                i=0, j;127			// the length of the value exceeds the available space128			if (nLen < sEscapedValue.length) {129				for (j = sEscapedValue.length; i < j; i += nLen) {130					aValues.push(sEscapedValue.substr(i, nLen));131				}132			} else {133				aValues.push(sEscapedValue);134			}135			// Google recommends using INSERT instead of update, because it is faster136			_driver.execute('BEGIN');137			_driver.execute('DELETE FROM ' + TABLE_NAME + ' WHERE key="' + sEscapedKey + '" AND location="' + sEscapedLocation + '"');138			for (i = 0, j = aValues.length; i < j; i += 1) {139				_driver.execute('INSERT INTO ' + TABLE_NAME + ' VALUES ("' + sEscapedKey + '", "' + sEscapedLocation + '", "' + aValues[i] + '")');140			}141			_driver.execute('COMMIT');142			143			return true;144		}145	});146	// releases the engine when the page unloads147	Util.Event.on('unload', function() {148		if (_driver) {_driver.close();}149	});150    StorageEngineGears.ENGINE_NAME = 'gears';151	StorageEngineGears.GEARS = 'beta.database';152	StorageEngineGears.DATABASE = 'yui.database';153	StorageEngineGears.isAvailable = function() {154		if (('google' in window) && ('gears' in window.google)) {155			try {...

Full Screen

Full Screen

api_test.js

Source:api_test.js Github

copy

Full Screen

1/* jshint node: true */2// TODO: Write a YouTube API mock to test without loading the real video, the result is too unpredictable3/*var should = require('should'); // jshint ignore:line4var url = require('url');5describe('Test basic API commands for YouTube tech', function() {6  // YouTube sometime hate us and sometime love us (pretty random)7  // We can't rely on this test to know if it really crash so we ignore his feeling8  it('should play and pause', function() {9    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));10    browser.driver.sleep(5000);11    browser.driver.executeScript('videojs("vid1").play()');12    browser.driver.sleep(5000);13    browser.driver.executeScript('return videojs("vid1").paused()').then(function(paused) {14      paused.should.be.false;15    });16    browser.driver.executeScript('videojs("vid1").pause();');17    browser.driver.sleep(5000);18    browser.driver.executeScript('return videojs("vid1").paused()').then(function(paused) {19      paused.should.be.true;20    });21  });22  it('should change the source with regular URL', function() {23    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));24    browser.driver.sleep(5000);25    browser.driver.executeScript('videojs("vid1").src("https://www.youtube.com/watch?v=y6Sxv-sUYtM");');26    browser.driver.sleep(5000);27    browser.driver.executeScript('return videojs("vid1").src()').then(function(src) {28      src.should.equal('https://www.youtube.com/watch?v=y6Sxv-sUYtM');29    });30  });31  it('should change the source with Youtu.be URL', function() {32    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));33    browser.driver.sleep(5000);34    browser.driver.executeScript('videojs("vid1").src("https://www.youtu.be/watch?v=y6Sxv-sUYtM");');35    browser.driver.sleep(5000);36    browser.driver.executeScript('return videojs("vid1").src()').then(function(src) {37      src.should.equal('https://www.youtu.be/watch?v=y6Sxv-sUYtM');38    });39  });40  it('should change the source with Embeded URL', function() {41    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));42    browser.driver.sleep(5000);43    browser.driver.executeScript('videojs("vid1").src("https://www.youtube.com/embed/y6Sxv-sUYtM");');44    browser.driver.sleep(5000);45    browser.driver.executeScript('return videojs("vid1").src()').then(function(src) {46      src.should.equal('https://www.youtube.com/embed/y6Sxv-sUYtM');47    });48  });49  it('should change the source with playlist URL', function() {50    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));51    browser.driver.sleep(5000);52    browser.driver.executeScript(53      'videojs("vid1").src("http://www.youtube.com/watch?v=xjS6SftYQaQ&list=SPA60DCEB33156E51F");');54    browser.driver.sleep(5000);55    browser.driver.executeScript('return videojs("vid1").src()').then(function(src) {56      src.should.equal('http://www.youtube.com/watch?v=xjS6SftYQaQ&list=SPA60DCEB33156E51F');57    });58  });59  it('should seek at a specific time', function() {60    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));61    browser.driver.sleep(5000);62    browser.driver.executeScript('videojs("vid1").currentTime(10);');63    browser.driver.executeScript('return videojs("vid1").currentTime()').then(function(currentTime) {64      currentTime.should.equal(10);65    });66  });67  it('should know duration', function() {68    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));69    browser.driver.sleep(5000);70    browser.driver.executeScript('videojs("vid1").play()');71    browser.driver.sleep(5000);72    browser.driver.executeScript('return videojs("vid1").duration()').then(function(duration) {73      duration.should.be.within(227, 228);74    });75  });76  it('should set the volume, mute and unmute', function() {77    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));78    browser.driver.sleep(5000);79    browser.driver.executeScript('videojs("vid1").play()');80    browser.driver.sleep(5000);81    browser.driver.executeScript('videojs("vid1").volume(0.5)');82    browser.driver.sleep(5000);83    browser.driver.executeScript('return videojs("vid1").volume()').then(function(volume) {84      volume.should.equal(0.5);85    });86    browser.driver.executeScript('return videojs("vid1").muted()').then(function(muted) {87      muted.should.be.false; // jshint ignore:line88    });89    browser.driver.executeScript('videojs("vid1").play();videojs("vid1").muted(true);');90    browser.driver.sleep(5000);91    browser.driver.executeScript('return videojs("vid1").muted()').then(function(muted) {92      muted.should.be.true; // jshint ignore:line93    });94    browser.driver.executeScript('videojs("vid1").play();videojs("vid1").muted(false);');95    browser.driver.sleep(5000);96    browser.driver.executeScript('return videojs("vid1").muted()').then(function(muted) {97      muted.should.be.false; // jshint ignore:line98    });99  });100  it('should switch technologies', function() {101    browser.driver.get(url.resolve(browser.baseUrl, '/sandbox/index.html'));102    browser.driver.sleep(5000);103    browser.driver.executeScript('videojs("vid1").play()');104    browser.driver.executeScript('videojs("vid1").src({ src: "http://vjs.zencdn.net/v/oceans.mp4", ' +105      'type: "video/mp4" });');106    browser.driver.sleep(1000);107    browser.driver.executeScript('videojs("vid1").play()');108    browser.driver.sleep(5000);109    browser.driver.executeScript('videojs("vid1").src({src:"https://www.youtu.be/watch?v=y6Sxv-sUYtM", ' +110      'type: "video/youtube" });');111    browser.driver.sleep(5000);112    browser.driver.executeScript('videojs("vid1").play()');113    browser.driver.sleep(5000);114    browser.driver.executeScript('return videojs("vid1").src()').then(function(src) {115      src.should.equal('https://www.youtu.be/watch?v=y6Sxv-sUYtM');116    });117  });118});...

Full Screen

Full Screen

howto-toggle-button.e2etest.js

Source:howto-toggle-button.e2etest.js Github

copy

Full Screen

1/**2 * Copyright 2017 Google Inc. All rights reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/* eslint max-len: ["off"] */17const helper = require('../../tools/selenium-helper.js');18const expect = require('chai').expect;19const {Key, By} = require('selenium-webdriver');20describe('howto-toggle-button', function() {21  let success;22  const findToggleButton = _ => {23    window.expectedToggleButton = document.querySelector('[role=button]');24  };25  const isUnpressed = _ => {26    let isAriaUnpressed =27      !window.expectedToggleButton.hasAttribute('aria-pressed') ||28      window.expectedToggleButton.getAttribute('aria-pressed') === 'false';29    return isAriaUnpressed && window.expectedToggleButton.pressed === false;30  };31  const isPressed = _ => {32    let isAriaPressed = window.expectedToggleButton.getAttribute('aria-pressed') === 'true';33    return isAriaPressed && window.expectedToggleButton.pressed === true;34  };35  beforeEach(function() {36    return this.driver.get(`${this.address}/howto-toggle-button/demo.html`)37      .then(_ => helper.waitForElement(this.driver, 'howto-toggle-button'));38  });39  it('should check the toggle button on [space]', async function() {40    await this.driver.executeScript(findToggleButton);41    success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedToggleButton);42    expect(success).to.be.true;43    success = await this.driver.executeScript(isUnpressed);44    expect(success).to.be.true;45    await this.driver.actions().sendKeys(Key.SPACE).perform();46    success = await this.driver.executeScript(isPressed);47    expect(success).to.be.true;48  });49  it('should check the toggle button on [enter]', async function() {50    await this.driver.executeScript(findToggleButton);51    success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedToggleButton);52    expect(success).to.be.true;53    success = await this.driver.executeScript(isUnpressed);54    expect(success).to.be.true;55    await this.driver.actions().sendKeys(Key.ENTER).perform();56    success = await this.driver.executeScript(isPressed);57    expect(success).to.be.true;58  });59  it('should not be focusable when [disabled] is true', async function() {60    await this.driver.executeScript(findToggleButton);61    success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedToggleButton);62    expect(success).to.be.true;63    success = await this.driver.executeScript(_ => {64      window.expectedToggleButton.disabled = true;65      return document.activeElement != window.expectedToggleButton;66    });67    expect(success).to.be.true;68  });69  it('should check the toggle button on click', async function() {70    await this.driver.executeScript(findToggleButton);71    success = await this.driver.executeScript(isUnpressed);72    expect(success).to.be.true;73    await this.driver.findElement(By.css('[role=button]')).click();74    success = await this.driver.executeScript(isPressed);75    expect(success).to.be.true;76  });77});78describe('howto-toggle-button pre-upgrade', function() {79  let success;80  beforeEach(function() {81    return this.driver.get(`${this.address}/howto-toggle-button/demo.html?nojs`);82  });83  it('should handle attributes set before upgrade', async function() {84    await this.driver.executeScript(_ => window.expectedToggleButton = document.querySelector('howto-toggle-button'));85    await this.driver.executeScript(_ => window.expectedToggleButton.setAttribute('pressed', ''));86    await this.driver.executeScript(_ => _loadJavaScript());87    await helper.waitForElement(this.driver, 'howto-toggle-button');88    success = await this.driver.executeScript(_ =>89      window.expectedToggleButton.pressed === true &&90      window.expectedToggleButton.getAttribute('aria-pressed') === 'true'91    );92    expect(success).to.be.true;93  });94  it('should handle instance properties set before upgrade', async function() {95    await this.driver.executeScript(_ => window.expectedToggleButton = document.querySelector('howto-toggle-button'));96    await this.driver.executeScript(_ => window.expectedToggleButton.pressed = true);97    await this.driver.executeScript(_ => _loadJavaScript());98    await helper.waitForElement(this.driver, 'howto-toggle-button');99    success = await this.driver.executeScript(_ =>100      window.expectedToggleButton.hasAttribute('pressed') &&101      window.expectedToggleButton.getAttribute('aria-pressed') === 'true'102    );103    expect(success).to.be.true;104  });...

Full Screen

Full Screen

howto-checkbox.e2etest.js

Source:howto-checkbox.e2etest.js Github

copy

Full Screen

1/**2 * Copyright 2017 Google Inc. All rights reserved.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/* eslint max-len: ["off"] */17const helper = require('../../tools/selenium-helper.js');18const expect = require('chai').expect;19const {Key, By} = require('selenium-webdriver');20describe('howto-checkbox', function() {21  let success;22  const findCheckbox = _ => {23    window.expectedCheckbox = document.querySelector('[role=checkbox]');24  };25  const isUnchecked = _ => {26    let isAriaUnchecked =27      !window.expectedCheckbox.hasAttribute('aria-checked') ||28      window.expectedCheckbox.getAttribute('aria-checked') === 'false';29    return isAriaUnchecked && window.expectedCheckbox.checked === false;30  };31  const isChecked = _ => {32    let isAriaChecked = window.expectedCheckbox.getAttribute('aria-checked') === 'true';33    return isAriaChecked && window.expectedCheckbox.checked === true;34  };35  beforeEach(function() {36    return this.driver.get(`${this.address}/howto-checkbox/demo.html`)37      .then(_ => helper.waitForElement(this.driver, 'howto-checkbox'));38  });39  it('should check the checkbox on [space]', async function() {40    await this.driver.executeScript(findCheckbox);41    success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedCheckbox);42    expect(success).to.be.true;43    success = await this.driver.executeScript(isUnchecked);44    expect(success).to.be.true;45    await this.driver.actions().sendKeys(Key.SPACE).perform();46    success = await this.driver.executeScript(isChecked);47    expect(success).to.be.true;48  });49  it('should not be focusable when [disabled] is true', async function() {50    await this.driver.executeScript(findCheckbox);51    success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedCheckbox);52    expect(success).to.be.true;53    success = await this.driver.executeScript(_ => {54      window.expectedCheckbox.disabled = true;55      return document.activeElement != window.expectedCheckbox;56    });57    expect(success).to.be.true;58  });59  it('should check the checkbox on click', async function() {60    await this.driver.executeScript(findCheckbox);61    success = await this.driver.executeScript(isUnchecked);62    expect(success).to.be.true;63    await this.driver.findElement(By.css('[role=checkbox]')).click();64    success = await this.driver.executeScript(isChecked);65    expect(success).to.be.true;66  });67});68describe('howto-checkbox pre-upgrade', function() {69  let success;70  beforeEach(function() {71    return this.driver.get(`${this.address}/howto-checkbox/demo.html?nojs`);72  });73  it('should handle attributes set before upgrade', async function() {74    await this.driver.executeScript(_ => window.expectedCheckbox = document.querySelector('howto-checkbox'));75    await this.driver.executeScript(_ => window.expectedCheckbox.setAttribute('checked', ''));76    await this.driver.executeScript(_ => _loadJavaScript());77    await helper.waitForElement(this.driver, 'howto-checkbox');78    success = await this.driver.executeScript(_ =>79      window.expectedCheckbox.checked === true &&80      window.expectedCheckbox.getAttribute('aria-checked') === 'true'81    );82    expect(success).to.be.true;83  });84  it('should handle instance properties set before upgrade', async function() {85    await this.driver.executeScript(_ => window.expectedCheckbox = document.querySelector('howto-checkbox'));86    await this.driver.executeScript(_ => window.expectedCheckbox.checked = true);87    await this.driver.executeScript(_ => _loadJavaScript());88    await helper.waitForElement(this.driver, 'howto-checkbox');89    success = await this.driver.executeScript(_ =>90      window.expectedCheckbox.hasAttribute('checked') &&91      window.expectedCheckbox.getAttribute('aria-checked') === 'true'92    );93    expect(success).to.be.true;94  });...

Full Screen

Full Screen

safari-execute-e2e-specs.js

Source:safari-execute-e2e-specs.js Github

copy

Full Screen

...26    await deleteSession();27  });28  describe('mobile: x methods', function () {29    it('should run in native context', async () => {30      await driver.execute('mobile: scroll', {direction: 'down'}).should.not.be.rejected;31    });32  });33  describe('synchronous', function () {34    it('should bubble up javascript errors', async () => {35      await driver.execute(`'nan'--`).should.eventually.be.rejected;36    });37    it('should eval javascript', async () => {38      (await driver.execute('return 1')).should.be.equal(1);39    });40    it('should not be returning hardcoded results', async () => {41      (await driver.execute('return 1+1')).should.be.equal(2);42    });43    it(`should return nothing when you don't explicitly return`, async () => {44      expect(await driver.execute('1+1')).to.not.exist;45    });46    it('should execute code inside the web view', async () => {47      (await driver.execute(GET_RIGHT_INNERHTML)).should.be.ok;48      (await driver.execute(GET_WRONG_INNERHTML)).should.not.be.ok;49    });50    it('should convert selenium element arg to webview element', async () => {51      let el = await driver.elementById('useragent');52      await driver.execute(SCROLL_INTO_VIEW, [el]);53    });54    it('should catch stale or undefined element as arg', async () => {55      let el = await driver.elementById('useragent');56      return driver.execute(SCROLL_INTO_VIEW, [{'ELEMENT': (el.value + 1)}]).should.beRejected;57    });58    it('should be able to return multiple elements from javascript', async () => {59      let res = await driver.execute(GET_ELEM_BY_TAGNAME);60      expect(res).to.have.length.above(0);61    });62    it('should pass along non-element arguments', async () => {63      let arg = 'non-element-argument';64      (await driver.execute('var args = Array.prototype.slice.call(arguments, 0); return args[0];', [arg])).should.be.equal(arg);65    });66    it('should handle return values correctly', async () => {67      let arg = ['one', 'two', 'three'];68      (await driver.execute('var args = Array.prototype.slice.call(arguments, 0); return args;', arg)).should.eql(arg);69    });70  });71  describe('asynchronous', function () {72    it('should bubble up javascript errors', async () => {73      await driver.execute(`'nan'--`).should.eventually.be.rejected;74    });75    it('should execute async javascript', async () => {76      await driver.setAsyncScriptTimeout(1000);77      (await driver.executeAsync(`arguments[arguments.length - 1](123);`)).should.be.equal(123);78    });79    it('should timeout when callback is not invoked', async () => {80      await driver.setAsyncScriptTimeout(1000);81      await driver.executeAsync(`return 1 + 2`).should.eventually.be.rejected;82    });83  });...

Full Screen

Full Screen

JavascriptExecutor.js

Source:JavascriptExecutor.js Github

copy

Full Screen

1'use strict';2describe('JavascriptExecutor', function() {3  var assert = require('assert');4  var path = require('path');5  var driver = require(path.resolve(__dirname, '..', 'lib', 'driver')).driver;6  var wd = require(7      path.resolve(__dirname, '..', '..', 'src', 'webdriver-sync')8    );9  var WebElement = wd.WebElement;10  var TimeUnit = wd.TimeUnit;11  beforeEach(function() {12    driver.get('http://google.com');13  });14  after(function(){15    driver.quit();16  });17  describe('#executeScript', function() {18    it('can return a WebElement', function() {19      var el = driver.executeScript(20        'return document.querySelector("[name=q]");'21      );22      assert(el instanceof WebElement);23    });24    it('can return an array of WebElements', function() {25      var divs = driver.executeScript(26        'return document.querySelectorAll("div");'27      );28      divs.forEach(function(div) {29        assert(div instanceof WebElement);30      });31    });32    it('can return numbers', function() {33      assert.equal(driver.executeScript('return 5;'), 5);34    });35    it('can return strings', function() {36      assert.equal(driver.executeScript('return "boo";'), 'boo');37    });38    it('can return objects', function() {39      var result = driver.executeScript('return {asdf:5};');40      assert.equal(result.asdf, 5);41    });42    it('can return arrays', function() {43      var result = driver.executeScript('return ["boo"];');44      assert.equal(result[0], 'boo');45    });46    it('handles nested arrays and objects', function(){47      var result = driver.executeScript('return {arr:["boo"],obj:{asdf:5}};');48      assert.equal(result.arr[0]+result.obj.asdf, 'boo5');49    });50  });51  describe('#executeAsyncScript', function() {52    before(function(){53      driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);54    });55    it('can return a WebElement', function() {56      var el = driver.executeAsyncScript(57        wrapInAsync('document.querySelector("[name=q]")')58      );59      assert(el instanceof WebElement);60    });61    it('can return an array of WebElements', function() {62      var divs = driver.executeAsyncScript(63        wrapInAsync('document.querySelectorAll("div")')64      );65      divs.forEach(function(div) {66        assert(div instanceof WebElement);67      });68    });69    it('can return numbers', function() {70      assert.equal(driver.executeAsyncScript(wrapInAsync('5')), 5);71    });72    it('can return strings', function() {73      assert.equal(driver.executeAsyncScript(wrapInAsync('"boo"')), 'boo');74    });75    it('can return objects', function() {76      var result = driver.executeAsyncScript(wrapInAsync('{asdf:5}'));77      assert.equal(result.asdf, 5);78    });79    it('can return arrays', function() {80      var result = driver.executeAsyncScript(wrapInAsync('["boo"]'));81      assert.equal(result[0], 'boo');82    });83    it('handles nested arrays and objects', function(){84      var result = driver.executeAsyncScript(85        wrapInAsync('{arr:["boo"],obj:{asdf:5}}')86      );87      assert.equal(result.arr[0]+result.obj.asdf, 'boo5');88    });89  });90  function wrapInAsync(value){91    return 'var callback = arguments[arguments.length - 1];'92    + 'setTimeout(function(){'93    + '  callback('+value+');'94    + '}, 10);';95  }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1  withCapabilities({2  build();3driver.execute('mobile: scroll', {direction: 'down'});4driver.quit();5  withCapabilities({6  build();7driver.execute('mobile: scroll', {direction: 'down'});8driver.quit();9  withCapabilities({10  build();11driver.execute('mobile: scroll', {direction: 'down'});12driver.quit();13  withCapabilities({14  build();15driver.execute('mobile: scroll', {direction: 'down'});16driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const opts = {3    capabilities: {4    }5};6async function main() {7    const client = await wdio.remote(opts);8    await client.execute(function() {9    });10    await client.deleteSession();11}12main();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {remote} = require('webdriverio');2const opts = {3  capabilities: {4  },5};6(async () => {7  const client = await remote(opts);8  await client.execute(function() {9  });10})();11const {remote} = require('webdriverio');12const opts = {13  capabilities: {14  },15};16(async () => {17  const client = await remote(opts);18  await client.execute(function() {19  });20})();21const {remote} = require('webdriverio');22const opts = {23  capabilities: {24  },25};26(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new webdriver.Builder()2    .withCapabilities({3    })4    .build();5driver.execute('mobile: selectPickerWheelValue', {order: 'next', offset: 0.15});6var driver = new webdriver.Builder()7    .withCapabilities({8    })9    .build();10driver.execute('mobile: selectPickerWheelValue', {order: 'previous', offset: 0.15});11var driver = new webdriver.Builder()12    .withCapabilities({13    })14    .build();15driver.execute('mobile: selectPickerWheelValue', {order: 'next', offset: 0.15});16var driver = new webdriver.Builder()17    .withCapabilities({18    })19    .build();20driver.execute('mobile: selectPickerWheelValue', {order: 'next', offset: 0.15});21var driver = new webdriver.Builder()22    .withCapabilities({23    })24    .build();25driver.execute('mobile: selectPickerWheelValue', {order: 'next', offset: 0.15});26var driver = new webdriver.Builder()27    .withCapabilities({28    })29    .build();30driver.execute('mobile: selectPickerWheelValue', {order: 'next', offset: 0.15});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const expect = chai.expect;6const assert = chai.assert;7const should = chai.should();8const caps = {9};10const driver = wd.promiseChainRemote('localhost', 4723);11driver.init(caps).then(function () {12  return driver.execute('mobile: launchApp', {bundleId: 'com.apple.mobilesafari'});13}).then(function () {14}).then(function () {15  return driver.sleep(5000);16}).then(function () {17  return driver.quit();18}).catch(function (err) {19  console.log(err);20});

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const { assert } = require('chai');3const { exec } = require('child_process');4const { execSync } = require('child_process');5const { getDriver } = require('./initDriver');6const { getPlatform } = require('./initDriver');7const { getDevice } = require('./initDriver');8const { getDeviceName } = require('./initDriver');9const { getDeviceVersion } = require('./initDriver');10const { getDeviceUDID } = require('./initDriver');11const { getDevicePlatform } = require('./initDriver');12const { getDevicePlatformVersion } = require('./initDriver');13const { getDeviceOrientation } = require('./initDriver');14const { getDeviceLocale } = require('./initDriver');15const { getDeviceLanguage } = require('./initDriver');16const { getDeviceTimezone } = require('./initDriver');17const { getDeviceApp } = require('./initDriver');18const { getDeviceAppPackage } = require('./initDriver');19const { getDeviceAppActivity } = require('./initDriver');20const { getDeviceAppWaitPackage } = require('./initDriver');21const { getDeviceAppWaitActivity } = require('./initDriver');22const { getDeviceAutomationName } = require('./initDriver');23const { getDeviceBrowserName } = require('./initDriver');24const { getDevicePlatformName } = require('./initDriver');25const { getDevicePlatformVersion } = require('./initDriver');26const { getDeviceDeviceName } = require('./initDriver');27const { getDeviceUDID } = require('./initDriver');28const { getDeviceNewCommandTimeout } = require('./initDriver');29const { getDeviceFullReset } = require('./initDriver');30const { getDeviceNoReset } = require('./initDriver');31const { getDeviceAppWaitDuration } = require('./initDriver');32const { getDeviceAppWaitPackage } = require('./initDriver');33const { getDeviceAppWaitActivity } = require('./initDriver');34const { getDeviceAutoGrantPermissions } = require('./initDriver');35const { getDeviceUnicodeKeyboard } = require('./initDriver');36const { getDeviceResetKeyboard } = require('./initDriver');37const { getDeviceSkipDeviceInitialization } = require('./initDriver');38const { getDeviceSkipServerInstallation } = require('./initDriver');39const { getDeviceDisableWindowAnimation } = require('./initDriver');40const { getDeviceDisableAndroidWatchers }

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = require("wd").promiseChainRemote();2var caps = {3};4driver.init(caps).then(function () {5    return driver.execute("mobile: selectPickerWheelValue", [{6    }]);7}).then(function () {8    return driver.quit();9}).done();10var driver = require("wd").promiseChainRemote();11var caps = {12};13driver.init(caps).then(function () {14    return driver.execute("mobile: selectPickerWheelValue", [{15    }]);16}).then(function () {17    return driver.quit();18}).done();19var driver = require("wd").promiseChainRemote();20var caps = {21};22driver.init(caps).then(function () {23    return driver.execute("mobile: selectPickerWheelValue", [{24    }]);25}).then(function () {26    return driver.execute("mobile: selectPickerWheelValue", [{27    }]);28}).then(function () {29    return driver.quit();30}).done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6var should = chai.should();7var expect = chai.expect;8var desiredCaps = {9};10var driver = wd.promiseChainRemote('localhost', 4723);11driver.init(desiredCaps)12    .then(function () {13        return driver.execute('return document.documentElement.outerHTML.toString();');14    })15    .then(function (source) {16        console.log(source);17    })18    .catch(function (err) {19        console.log(err);20    });

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful