Best JavaScript code snippet using appium-xcuitest-driver
app.js
Source:app.js  
1"use strict";2/**3 *4 * @author xgqfrms5 * @license MIT6 * @copyright xgqfrms7 * @created 2019-08-128 *9 * @description IndexedDB All In One10 * @augments11 * @example12 * @link13 *14 */15let log = console.log;16const IndexDBDemo = (debug = false) => {17    let indexedDB = window.indexedDB || window.webkitIndexedDB;18    // let IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;19    // let dbVersion = 3.0;20    // let dbVersion = 2.0;21    let dbVersion = 1.0;22    let idb = ``;23    let db = ``;24    if (indexedDB) {25        // 1. create DB / read DB26        let idb_connect = indexedDB.open("xgqfrms_idb", dbVersion);27        window.idb_connect = window.idb_connect || idb_connect;28        // connect success29        idb_connect.onsuccess = function(e) {30            // 2. get db instanced31            let {32                readyState,33                error,34                source,35                transaction,36                result,37                // events: onerror/onblocked/onsucces/onupgradeneeded38            } = idb_connect;39            log("Success creating/accessing IndexedDB database", readyState);40            log(`idb_connect =`, idb_connect);41            // IDBOpenDBRequest42            idb = idb_connect.result;43            window.idb = window.idb || idb;44            log(`%c onsuccess idb =`, `color: #0f0;`, idb);45            // IDBDatabase46            let {47                name,48                version,49                objectStoreNames,50                // events: onclose/onerror/onabort/onversionchange51            } = idb;52            let length = objectStoreNames.length;53            // const storeNames = [`othersDB`, `selfDB`, `errorDB`];54            // if (!length) {55            //     storeNames.forEach(56            //         (name, i) => {57            //             let store = idb.createObjectStore(58            //                 name,59            //                 {60            //                     keyPath: "uid",61            //                 },62            //             );63            //             log(`store`, store);64            //         }65            //     );66            // } else {67            //     // exist68            // }69            idb.onclose = function(e) {70                log("onclose creating/accessing IndexedDB", e);71            };72            idb.onerror = function(e) {73                log("onerror creating/accessing IndexedDB", e);74            };75            idb.onabort = function(e) {76                log("onabort creating/accessing IndexedDB", e);77            };78            idb.onversionchange = function(e) {79                log("onversionchange creating/accessing IndexedDB", e);80                // const storeNames = [`othersDB`, `selfDB`, `errorDB`];81                // if (!length) {82                //     storeNames.forEach(83                //         (name, i) => {84                //             let store = idb.createObjectStore(85                //                 name,86                //                 {87                //                     keyPath: "uid",88                //                 },89                //             );90                //             log(`store`, store);91                //         }92                //     );93                // } else {94                //     // exist95                // }96            };97        };98        // connect erorr99        idb_connect.onerror = function(e) {100            let {101                readyState,102                error,103                source,104                transaction,105                result,106                // events: onerror/onblocked/onsucces/onupgradeneeded107            } = idb_connect;108            log("Error creating/accessing IndexedDB database", readyState, error);109        };110        // connect blocked111        idb_connect.onblocked = function(e) {112            let {113                readyState,114                error,115                source,116                transaction,117                result,118                // events: onerror/onblocked/onsucces/onupgradeneeded119            } = idb_connect;120            log("Blocked creating/accessing IndexedDB database", readyState);121        };122        // connect upgradeneeded123        idb_connect.onupgradeneeded = function(e) {124            let {125                readyState,126                error,127                source,128                transaction,129                result,130                // events: onerror/onabort/onversionchange/onclose131            } = idb_connect;132            log("Upgradeneeded & IndexedDB database", readyState);133            log(`idb_connect =`, idb_connect);134            idb = idb_connect.result;135            window.idb = window.idb || idb;136            log(`%c onupgradeneeded idb =`, `color: #f0f`, idb);137            let {138                name,139                version,140                objectStoreNames,141                // events: onclose/onerror/onabort/onversionchange142            } = idb;143            let length = objectStoreNames.length;144            const storeNames = [`othersDB`, `selfDB`, `errorDB`];145            if (!length) {146                storeNames.forEach(147                    (name, i) => {148                        let store = idb.createObjectStore(149                            name,150                            {151                                keyPath: "uid",152                            },153                        );154                        let msgIdIndex = store.createIndex("by_msgId", "msgId", {unique: true});155                        let timestampIndex = store.createIndex("by_timestamp", "timestamp");156                        if (name === `othersDB`) {157                            store.add({158                                msgId: 20190812133137,159                                timestamp: new Date().getTime(),160                                uid: 7654321,161                            })162                        }163                        log(`store`, store);164                        log(`msgIdIndex`, msgIdIndex);165                        log(`timestampIndex`, timestampIndex);166                    }167                );168            } else {169                // exist170            }171            idb.onclose = function(e) {172                log("IndexedDB onupgradeneeded onclose", idb);173            };174            idb.onerror = function(e) {175                log("IndexedDB onupgradeneeded onerror", idb);176            };177            idb.onabort = function(e) {178                log("IndexedDB onupgradeneeded onabort", idb);179            };180            idb.onversionchange = function(e) {181                log("IndexedDB onupgradeneeded onversionchange", idb);182                // const storeNames = [`othersDB`, `selfDB`, `errorDB`];183                // if (!length) {184                //     storeNames.forEach(185                //         (name, i) => {186                //             let store = idb.createObjectStore(187                //                 name,188                //                 {189                //                     keyPath: "uid",190                //                 },191                //             );192                //             log(`store`, store);193                //         }194                //     );195                // } else {196                //     // exist197                // }198            };199        };200    } else {201        alert(`your browser not support indexedDB!`);202    }203};204const idbTest = () => {205    let writerBtn = document.querySelector(`[data-dom="data-btn-write"]`);206    let readBtn = document.querySelector(`[data-dom="data-btn-read"]`);207    let textarea = document.querySelector(`#show_idb`);208    // write209    writerBtn.addEventListener(`click`, () => {210        log(`async window.idb `, window.idb);211        if (window.idb) {212            let {213                name,214                version,215                objectStoreNames,216                // events: onclose/onerror/onabort/onversionchange217            } = idb;218            let length = objectStoreNames.length;219            log(`write data to idb!`, length);220            let obj = {221                // msgId: btoa(new Date().getTime()),// base64 bug222                msgId: new Date().getTime() + 1024,223                timestamp: new Date().getTime(),224                uid: 1234567,225            };226            let options = {227                datas: [obj],228                storeName: "othersDB",229            };230            textarea.innerHTML = ``;231            textarea.value = JSON.stringify(obj, null, 4);232            writeStoreDatas(options);233        }234    });235    // read236    readBtn.addEventListener(`click`, () => {237        log(`async window.idb `, window.idb);238        if (window.idb) {239            let {240                name,241                version,242                objectStoreNames,243                error,244            } = idb;245            log(`read data from idb!`, objectStoreNames);246            let options = {247                // datas: [obj],248                indexName: "by_msgId",249                storeName: "othersDB",250            };251            let data = readStoreDatas(options);252            log(`read store data`, data);253            // textarea.innerHTML = ``;254            // textarea.value = JSON.stringify(data, null, 4);255        }256    });257};258const writeStoreDatas = (options = {}) => {259    let idb = window.idb;260    if (idb) {261        let {262            name,263            version,264            objectStoreNames,265            error,266        } = idb;267        let length = objectStoreNames.length;268        log(`writeStoreDatas `, objectStoreNames, length);269        // DOMStringList {0: "errorDB", 1: "othersDB", 2: "selfDB", length: 3} 3270        let storeNames = [...objectStoreNames];271        let {272            datas,273            storeName,274        } = options;275        if (storeNames.includes(storeName)) {276            // transaction277            let tx = idb.transaction(storeName, "readwrite");278            log(`transaction `, tx);279            // IDBTransaction280            tx.onabort = function(e) {281                log(`transaction onabort`, e);282            };283            tx.onerror = function(e) {284                log(`transaction onerror`, e);285            };286            tx.oncomplete = function(e) {287                log(`transaction oncomplete`, e);288                log(`All requests have succeeded and the transaction has committed.`);289            };290            let opened_store = tx.objectStore(storeName);291            log(`opened_store `, opened_store);292            // IDBObjectStore293            // let {294            //     autoIncrement,295            //     indexNames,296            //     keyPath,297            //     name,298            //     transaction: {299            //         db: {300            //             //301            //         },302            //         error,303            //         mode, // "readwrite"/ "readonly"304            //         objectStoreNames,305            //         // events: onabort, oncomplete, onerror306            //     },307            // } = opened_store;308            datas.forEach(obj => opened_store.put(obj));309        } else {310            alert(`no exsit this store!`);311        }312    }313};314const readStoreDatas = (options = {}, callback = (obj) => log(`read idb callback`, obj)) => {315    window.DATA = window.DATA || {};316    let result = ``;317    let idb = window.idb;318    if (idb) {319        let {320            name,321            version,322            objectStoreNames,323            error,324        } = idb;325        let length = objectStoreNames.length;326        log(`readStoreDatas `, objectStoreNames, length);327        // DOMStringList {0: "errorDB", 1: "othersDB", 2: "selfDB", length: 3} 3328        let storeNames = [...objectStoreNames];329        let {330            datas,331            storeName,332            indexName,333        } = options;334        if (storeNames.includes(storeName)) {335            // transaction336            let tx = idb.transaction(storeName, "readonly");337            log(`transaction `, tx);338            // IDBTransaction339            tx.onabort = function(e) {340                log(`transaction onabort`, e);341            };342            tx.onerror = function(e) {343                log(`transaction onerror`, e);344            };345            tx.oncomplete = function(e) {346                log(`transaction oncomplete`, e);347                log(`All requests have succeeded and the transaction has committed.`);348                // return result;349                customizeEvent(true);350            };351            let opened_store = tx.objectStore(storeName);352            log(`opened_store `, opened_store);353            let index_store = opened_store.index("by_msgId");354            log(`index_store `, index_store);355            // query356            let request = index_store.get(20190812133137);357            log(`index_store request `, request);358            request.onsuccess = function(e) {359                let matching = request.result;360                log(`index_store request matching `, matching);361                if (matching !== undefined) {362                    let {363                        uid,364                        msgId,365                        timestamp,366                    } = matching;367                    log(`A match was found.`, JSON.stringify(matching, null, 4));368                    result = matching;369                    window.DATA = matching;370                    // callback371                    callback(window.DATA);372                } else {373                    log(`No match was found.`, e);374                }375            };376            // IDBObjectStore377            // let {378            //     autoIncrement,379            //     indexNames,380            //     keyPath,381            //     name,382            //     transaction: {383            //         db: {384            //             //385            //         },386            //         error,387            //         mode, // "readwrite"/ "readonly"388            //         objectStoreNames,389            //         // events: onabort, oncomplete, onerror390            //     },391            // } = opened_store;392        } else {393            alert(`no exsit this store!`);394        }395    }396    // return result;397    setTimeout(() => {398        log(`return result `, result);399        return result;400    }, 3000);401};402const customizeEvent = (flag = false) => {403    let event = new CustomEvent("autoReadStoreData", {404        detail: {405            isFinished: flag,406        },407        bubbles: true,408        cancelable: true,409    });410    document.querySelector(`html`).dispatchEvent(event);411    log(`%c autoReadStoreData dispatchEvent`, `color: red;`, event);412};413const autoShowReadData = () => {414    let data = window.DATA || {};415    log(`read store data`, data);416    let textarea = document.querySelector(`#show_idb`);417    textarea.innerHTML = ``;418    textarea.value = JSON.stringify(data, null, 4);419};420document.addEventListener(`autoReadStoreData`, autoShowReadData, false);421window.addEventListener(`DOMContentLoaded`, (e) => {422    log(`DOM fully loaded and parsed!`, e);423    IndexDBDemo();424    idbTest();425});426const idb_operations = (idb, datas = []) => {427    let storeWirte = (datas = []) => {428        let store = idb.createObjectStore("books", {keyPath: "isbn"});429        // create index430        let titleIndex = store.createIndex("by_title", "title", {unique: true});431        let authorIndex = store.createIndex("by_author", "author");432        // Populate with initial data.433        store.add({434            title: "Quarry Memories",435            author: "Fred",436            isbn: 123456,437        });438        store.put({439            title: "Water Buffaloes",440            author: "Fred",441            isbn: 234567,442        });443    };444    let storeUpdate = (datas = []) => {445        // transaction446        let tx = idb.transaction("books", "readwrite");447        let opened_store = tx.objectStore("books");448        opened_store.put({449            title: "Quarry Memories",450            author: "Fred",451            isbn: 123456,452        });453        opened_store.put({454            title: "Water Buffaloes",455            author: "Fred",456            isbn: 234567,457        });458        opened_store.put({459            title: "Bedrock Nights",460            author: "Barney",461            isbn: 345678,462        });463        tx.oncomplete = function() {464            log(`All requests have succeeded and the transaction has committed.`);465        };466    };467    let storeRead = (datas = []) => {468        // index & looks up469        let tx = idb.transaction("books", "readonly");470        let opened_store = tx.objectStore("books");471        let index = opened_store.index("by_title");472        // query473        let request = index.get("Bedrock Nights");474        request.onsuccess = function() {475            let matching = request.result;476            if (matching !== undefined) {477                let {478                    isbn,479                    title,480                    author,481                } = matching;482                log(`A match was found.`, isbn, title, author);483            } else {484                log(`No match was found.`);485            }486        };487    };488    return {489        storeWirte,490        storeUpdate,491        storeRead,492    };493};494(() => {495    log(`IIFE function!`);496    IndexDBDemo();497    idbTest();...idb.js
Source:idb.js  
1/* 2   Copyright 2019 Locomote Ltd.3   Licensed under the Apache License, Version 2.0 (the "License");4   you may not use this file except in compliance with the License.5   You may obtain a copy of the License at6       http://www.apache.org/licenses/LICENSE-2.07   Unless required by applicable law or agreed to in writing, software8   distributed under the License is distributed on an "AS IS" BASIS,9   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10   See the License for the specific language governing permissions and11   limitations under the License.12*/13/* Functions for working with IndexedDB databases. */14/**15 * Initialize the IndexedDB API.16 * @param global    A global object with { indexedDB, IDBKeyRange } properties.17 * @return Returns a set of functions for interacting with an IndexedDB instance.18 */19function initIDB( global ) {20    const { indexedDB, IDBKeyRange } = global;21    /**22     * Open an IndexedDB connection.23     * @param schema    The database schema.24     */25    function idbOpen( schema ) {26        const { name, version = 1 } = schema;27        if( !name ) {28            throw new Error('idbOpen: "name" property not specified on schema');29        }30        return new Promise( ( resolve, reject ) => {31            const request = indexedDB.open( name, version );32            request.onsuccess = ( e ) => {33                resolve( request.result );34            };35            request.onerror = ( e ) => {36                reject( request.error );37            };38            request.onupgradeneeded = ( e ) => {39                idbInit( e.target.result, schema );40            };41        });42    }43    /**44     * Initialize an IndexedDB instance.45     * @param db        The DB connection.46     * @param schema    The DB schema.47     */48    function idbInit( db, schema ) {49        const { stores } = schema;50        for( const name in stores ) {51            const { options, indexes } = stores[name];52            const objStore = db.createObjectStore( name, options );53            for( const index in indexes ) {54                const { keyPath, options } = indexes[index];55                objStore.createIndex( index, keyPath, options );56            }57        }58    }59    /**60     * Convert an idb request object to a promise.61     */62    function reqAsPromise( request ) {63        return new Promise( ( resolve, reject ) => {64            request.onsuccess = () => resolve( request.result );65            request.onerror   = () => reject( request.error );66        });67    }68    /**69     * Connect to a named object store of a database instance.70     * @param schema    The database schema.71     * @param store     The name of the object store being connected to.72     */73    async function idbConnect( schema, store ) {74        // The database connection.75        const db = await idbOpen( schema );76        // Start a new transaction and return a reference to the object store.77        function openObjStore( mode = 'readonly' ) {78            // Start a new transaction.79            const tx = db.transaction( store, mode );80            // Open object store.81            return tx.objectStore( store );82        }83        // Read some metadata from the object store.84        const { keyPath, indexNames } = openObjStore();85        /**86         * Read an object from an object store.87         * @param key       An object primary key.88         * @param objStore  An optional reference to an already opened object store.89         */90        function read( key, objStore = openObjStore() ) {91            return reqAsPromise( objStore.get( key ) );92        }93        /**94         * Read a list of objects from an object store.95         * @param keys  A list of object primary keys.96         */97        function readAll( keys ) {98            const objStore = openObjStore();99            return Promise.all( keys.map( key => {100                return read( key, objStore );101            }));102        }103        /**104         * Write an object to an object store.105         * @param object    The object to write.106         */107        function write( object ) {108            const objStore = openObjStore('readwrite');109            return reqAsPromise( objStore.put( object ) );110        }111        /**112         * Delete an object from an object store.113         * @param key   An object primary key.114         */115        function remove( key ) {116            const objStore = openObjStore('readwrite');117            return reqAsPromise( objStore.delete( key ) );118        }119        /**120         * Open a cursor on an object store's primary key index.121         * @param term  An index filter term.122         */123        function openPK( term ) {124            const objStore = openObjStore();125            return objStore.openCursor( term );126        }127        /**128         * Open a cursor on an object store index.129         * @param index The name of the index to open.130         * @param term  An index filter term.131         */132        function openIndex( index, term ) {133            const objStore = openObjStore();134            return objStore.index( index ).openCursor( term );135        }136        /**137         * Count the number of items in an index.138         * @param index The name of the index to open.139         * @param term  An index filter term.140         */141        async function indexCount( index, term ) {142            const objStore = openObjStore();143            return reqAsPromise( objStore.index( index ).count( term ) );144        }145        /**146         * Close the database.147         */148        function close() {149            db.close();150        }151        // Return the API.152        return {153            keyPath,154            indexNames,155            read,156            readAll,157            write,158            remove,159            openPK,160            openIndex,161            indexCount,162            close163        };164    }165    return {166        indexedDB,167        IDBKeyRange,168        idbOpen,169        idbInit,170        idbConnect171    };172        173}174if( typeof module === 'object' ) {175    module.exports = initIDB;...IdbService.js
Source:IdbService.js  
1/**2 * Copyright (c) 2015-present, Facebook, Inc.3 * All rights reserved.4 *5 * This source code is licensed under the license found in the LICENSE file in6 * the root directory of this source tree.7 *8 * @flow strict-local9 * @format10 */11import type {NuclideUri} from 'nuclide-commons/nuclideUri';12import type {ConnectableObservable} from 'rxjs';13import type {IdbDevice} from './types';14import {observeProcess, runCommand} from 'nuclide-commons/process';15import {Observable} from 'rxjs';16import {getAvailableServerPort} from 'nuclide-commons/serverPort';17import fsPromise from 'nuclide-commons/fsPromise';18import {parseIdbJsonOutput} from './Parsing';19export type IdbDaemonReadyMessage = {20  port: number,21};22function filterStdout(msg): Observable<string> {23  return msg.kind === 'stdout' ? Observable.of(msg.data) : Observable.empty();24}25export function startDaemon(): ConnectableObservable<IdbDaemonReadyMessage> {26  return Observable.defer(() => getAvailableServerPort())27    .switchMap(port =>28      observeProcess('idb', [29        'daemon',30        '--json',31        '--daemon-port',32        port.toString(),33      ])34        .concatMap(filterStdout)35        .map(line => JSON.parse(line)),36    )37    .publish();38}39export type IdbCompanionReadyMessage = {40  hostname: string,41  thrift_port: number,42};43export function startCompanion(44  udid: string,45): ConnectableObservable<IdbCompanionReadyMessage> {46  return Observable.defer(() => fsPromise.tempdir())47    .switchMap(tempDir =>48      observeProcess('idb_companion', ['--udid', udid, '--json'], {49        cwd: tempDir,50      })51        .concatMap(filterStdout)52        .map(line => JSON.parse(line)),53    )54    .publish();55}56export async function listTargets(): Promise<Array<IdbDevice>> {57  const output = await runCommand('idb', ['list-targets', '--json'])58    .catch(e => {59      if (e.stdout != null) {60        e.message += `\n\n${e.stdout}`;61      }62      throw e;63    })64    .timeout(5000)65    .toPromise();66  return parseIdbJsonOutput(output);67}68export type IdbConnectMessage = {69  udid: string,70};71export function connect(72  companionHostname: string,73  companionPort: number,74  options?: {daemonHostname?: string, daemonPort?: number} = {},75): ConnectableObservable<IdbConnectMessage> {76  const args = [77    'connect',78    '--json',79    companionHostname,80    companionPort.toString(),81  ];82  if (typeof options.daemonHostname === 'string') {83    args.push('--daemon-host', options.daemonHostname);84  }85  if (typeof options.daemonPort === 'number') {86    args.push('--daemon-port', options.daemonPort.toString());87  }88  return observeProcess('idb', args)89    .concatMap(filterStdout)90    .map(line => JSON.parse(line))91    .publish();92}93export async function connectToDaemon(94  hostname: string,95  port: number,96): Promise<void> {97  await runCommand('idb', [98    'connect',99    '--daemon',100    hostname,101    port.toString(),102  ]).toPromise();103}104export async function disconnectFromDaemon(105  hostname: string,106  port: number,107): Promise<void> {108  await runCommand('idb', [109    'disconnect',110    '--daemon',111    hostname,112    port.toString(),113  ]).toPromise();114}115export type IdbInstallMessage = {116  installedAppBundleId: string,117};118export function install(119  bundlePath: NuclideUri,120  options?: {daemonHostname?: string, daemonPort?: number} = {},121): ConnectableObservable<IdbInstallMessage> {122  const args = ['install', '--json', bundlePath];123  if (typeof options.daemonHostname === 'string') {124    args.push('--daemon-host', options.daemonHostname);125  }126  if (typeof options.daemonPort === 'number') {127    args.push('--daemon-port', options.daemonPort.toString());128  }129  return observeProcess('idb', args)130    .concatMap(filterStdout)131    .map(line => JSON.parse(line))132    .publish();...gen.js
Source:gen.js  
1const idb = require('../idb');2const assert = require('assert');3const initGlobal = require('indexeddbshim');4// A global environment for the IndexedDB shim.5const global = {};6global.window = global;7// Initialize the global env by adding indexedDB and IDBKeyPath refs.8initGlobal( global, { checkOrigin: false, memoryDatabase: ':memory:' });9const {10    idbConnect11} = idb( global );12const schema = {13    name: 'test',14    version: 1,15    stores: {16        'fruit': {17            options: { keyPath: 'name' },18            indexes: {19                color: {20                    keyPath: 'color',21                    options: { unique: false }22                }23            }24        }25    }26}27const fruits = [28    { name: 'apple', color: 'green' },29    { name: 'banana', color: 'yellow' },30    { name: 'grape', color: 'purple' },31    { name: 'pineapple', color: 'yellow' },32    { name: 'orange', color: 'orange' }33];34async function populateDB() {35    const { write } = await idbConnect( schema, 'fruit');36    await Promise.all( fruits.map( fruit => {37        return write( fruit );38    }));39}40describe('generator', function() {41    before( populateDB );42    it('next', async function() {43        const { openPK, read } = await idbConnect( schema, 'fruit');44        async function makePK() {45            return new Promise( ( resolve, reject ) => {46                const request = openPK();47                const results = [];48let first = true;49                request.onsuccess = () => {50                    let cursor = request.result;51                    if( cursor ) {52                        results.push( cursor.primaryKey );53                        cursor.continue();54                    }55                    //else {56                    if( first ) { first = false;57                        resolve( function* genPK() {58                            while( results.length ) {59console.log('results.length=',results.length);60                                yield results.shift();61                                /*62                                const key = results.shift();63                                return read( key );64                                */65                            }66                        });67                    }68                }69                request.onerror = reject;70            });71        }72        const pk = await makePK();73        for( const x of pk() ) {74            console.log( x );75        }76        /*77        let i = 0;78        let pkIterable = await iteratePK();79        for ( const x of pkIterable ) {80            console.log('>', x );81            //assert.equal( x.value, fruits[i++].name );82        }83        */84    });...main.js
Source:main.js  
1const idb = require('../idb');2const assert = require('assert');3const initGlobal = require('indexeddbshim');4// A global environment for the IndexedDB shim.5const global = {};6global.window = global;7// Initialize the global env by adding indexedDB and IDBKeyPath refs.8initGlobal( global, { checkOrigin: false, memoryDatabase: ':memory:' });9const {10    idbConnect11} = idb( global );12const schema = {13    name: 'test',14    version: 1,15    stores: {16        'fruit': {17            options: { keyPath: 'name' },18            indexes: {19                color: {20                    keyPath: 'color',21                    options: { unique: false }22                }23            }24        }25    }26}27const fruits = [28    { name: 'apple', color: 'green' },29    { name: 'banana', color: 'yellow' },30    { name: 'grape', color: 'purple' },31    { name: 'pineapple', color: 'yellow' },32    { name: 'orange', color: 'orange' }33];34async function populateDB() {35    const { write } = await idbConnect( schema, 'fruit');36    await Promise.all( fruits.map( fruit => {37        return write( fruit );38    }));39}40describe('read/write', function() {41    before( populateDB );42    it('read', async function() {43        const { read } = await idbConnect( schema, 'fruit');44        const key = fruits[0].name;45        const obj = await read( key );46        assert.equal( obj.name, key );47    });48    it('readAll', async function() {49        const { readAll } = await idbConnect( schema, 'fruit');50        const keys = fruits.map( f => f.name );51        const objects = await readAll( keys );52        assert.equal( objects.length, fruits.length );53    });54    it('indexCount', async function() {55        const { indexCount } = await idbConnect( schema, 'fruit');56        const count = await indexCount('color', 'yellow' );57        assert.equal( count, fruits.filter( f => f.color == 'yellow' ).length );58    });59});60describe('remove', function() {61    before( populateDB );62    it('remove', async function() {63        const { remove, read } = await idbConnect( schema, 'fruit');64        const key = fruits[0].name;65        await remove( key );66        const obj = await read( key );67        assert.equal( obj, null );68    });69});70describe('meta', function() {71    before( populateDB );72    it('keyPath', async function() {73        const { keyPath } = await idbConnect( schema, 'fruit');74        assert.equal( keyPath, 'name');75    });76    it('indexNames', async function() {77        const { indexNames } = await idbConnect( schema, 'fruit');78        assert.equal( indexNames.length, 1 );79        assert.equal( indexNames[0], 'color');80    });...idb-e2e-specs.js
Source:idb-e2e-specs.js  
...28        udid: simctl.udid,29      });30      await simctl.bootDevice();31      await simctl.startBootMonitor();32      await idb.connect({onlineTimeout: 10000});33    });34    after(async function () {35      await idb.disconnect();36      try {37        await simctl.shutdownDevice();38      } catch (ign) {}39    });40    // TODO: getting the description returns data in a format that is a pain41    // to parse.42    it.skip('should be able to call connect/disconnect multiple times', async function () {43      await idb.connect();44      await assertDeviceDescription(idb, simctl.udid);45      await idb.disconnect();46    });47  });48  describe('connect/disconnect (non booted device)', function () {49    let idb;50    before(async function () {51      idb = new IDB({52        udid: simctl.udid,53      });54      try {55        await simctl.shutdownDevice();56      } catch (ign) {}57    });58    beforeEach(async function () {59      await idb.connect();60    });61    afterEach(async function () {62      await idb.disconnect();63    });64    it('should be able to call connect multiple times', async function () {65      await idb.connect().should.be.eventually.fulfilled;66    });67    it('should be able to call disconnect multiple times', async function () {68      await idb.disconnect().should.be.eventually.fulfilled;69    });70  });71  describe('connect an invalid device', function () {72    it('should throw if no udid is provided', function () {73      should.throw(() => new IDB());74    });75    it('should throw if invalid udid is provided', async function () {76      const idb = new IDB({udid: 'blabla'});77      await idb.connect().should.eventually.be.rejected;78    });79  });...interaction-commands-e2e-specs.js
Source:interaction-commands-e2e-specs.js  
...14    simctl = await prepareDevice();15    idb = new IDB({16      udid: simctl.udid,17    });18    await idb.connect({onlineTimeout: 10000});19  });20  after(async function () {21    await idb.disconnect();22    await deleteDevice(simctl);23  });24  it('tap', async function () {25    await idb.tap(100, 100).should.be.fulfilled;26  });27  it('pressButton', async function () {28    await idb.pressButton('HOME').should.be.fulfilled;29  });30  it('pressKeycode', async function () {31    await idb.pressKeycode(4, {32      duration: 2,...crashlog-commands-e2e-specs.js
Source:crashlog-commands-e2e-specs.js  
...15    simctl = await prepareDevice();16    idb = new IDB({17      udid: simctl.udid,18    });19    await idb.connect({onlineTimeout: 10000});20  });21  after(async function () {22    await idb.disconnect();23    await deleteDevice(simctl);24  });25  it('listCrashLogs', async function () {26    const crashes = await idb.listCrashLogs();27    _.isArray(crashes).should.be.true;28  });29  it('deleteCrashLogs', async function () {30    await idb.deleteCrashLogs({all: true}).should.be.fulfilled;31  });...Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var idb = require('appium-xcuitest-driver').idb;5var driver = new webdriver.Builder()6    .forBrowser('selenium')7    .build();8driver.findElement(By.name('q')).sendKeys('webdriver');9driver.findElement(By.name('btnK')).click();10driver.wait(until.titleIs('webdriver - Google Search'), 1000);11driver.quit();12var idb = require('appium-xcuitest-driver').idb;13idb.connect('myDevice', 'myBundleId', function(err, res) {14  console.log(err, res);15});16var idb = require('appium-xcuitest-driver').idb;17idb.list(function(err, res) {18  console.log(err, res);19});20var idb = require('appium-xcuitest-driver').idb;21idb.install('myDevice', 'myBundleId', function(err, res) {22  console.log(err, res);23});24var idb = require('appium-xcuitest-driver').idb;25idb.launch('myDevice', 'myBundleId', function(err, res) {26  console.log(err, res);27});28var idb = require('appium-xcuitest-driver').idb;29idb.uninstall('myDevice', 'myBundleId', function(err, res) {30  console.log(err, res);31});32var idb = require('appium-xcuitest-driver').idb;33idb.getFiles('myDevice', 'myBundleId', function(err, res) {34  console.log(err, res);35});Using AI Code Generation
1const idb = require('idb');2async function main() {3  const idbConnection = await idb.connect();4  const devices = await idbConnection.listDevices();5  console.log(devices);6}7main();Using AI Code Generation
1var idb = require('appium-xcuitest-driver').idb;2var idbClient = idb.connect('localhost', 27753);3idbClient.listApps().then(function (apps) {4    console.log('apps:', apps);5});6var idb = require('appium-xcuitest-driver').idb;7var idbClient = idb.connect('localhost', 27753);8idbClient.listApps().then(function (apps) {9    console.log('apps:', apps);10});11var idb = require('appium-xcuitest-driver').idb;12var idbClient = idb.connect('localhost', 27753);13idbClient.listApps().then(function (apps) {14    console.log('apps:', apps);15});16var idb = require('appium-xcuitest-driver').idb;17var idbClient = idb.connect('localhost', 27753);18idbClient.listApps().then(function (apps) {19    console.log('apps:', apps);20});21var idb = require('appium-xcuitest-driver').idb;22var idbClient = idb.connect('localhost', 27753);23idbClient.listApps().then(function (apps) {24    console.log('apps:', apps);25});26var idb = require('appium-xcuitest-driver').idb;27var idbClient = idb.connect('localhost', 27753);28idbClient.listApps().then(function (apps) {29    console.log('apps:', apps);30});31var idb = require('appium-xcuitest-driver').idb;32var idbClient = idb.connect('localhost', 27753);33idbClient.listApps().then(function (appsUsing AI Code Generation
1var idb = require('idb');2var idbPromise = idb.connect('com.apple.podcasts');3var idb = require('idb');4var idbPromise = idb.connect('com.apple.podcasts');5var idb = require('idb');6var idbPromise = idb.connect('com.apple.podcasts');7var idb = require('idb');8var idbPromise = idb.connect('com.apple.podcasts');9var idb = require('idb');10var idbPromise = idb.connect('com.apple.podcasts');11var idb = require('idb');12var idbPromise = idb.connect('com.apple.podcasts');13var idb = require('idb');14var idbPromise = idb.connect('com.apple.podcasts');15var idb = require('idb');16var idbPromise = idb.connect('com.apple.podcasts');17var idb = require('idb');18var idbPromise = idb.connect('com.apple.podcasts');19var idb = require('idb');20var idbPromise = idb.connect('com.apple.podcasts');21var idb = require('idb');22var idbPromise = idb.connect('com.apple.podcasts');Using AI Code Generation
1var idb = require('appium-idb');2var idbConnect = idb.connect;3var idbExec = idb.exec;4var appiumSession = 'f9a1a7c8-0f8a-4e0d-8d1b-1e8f6b7d6d2c';5var udid = '00008030-000F6D3E0A30002E';6var idbClient = await idbConnect(udid, appiumSession);7var result = await idbExec(idbClient, 'list_apps');8console.log(result);9await idbClient.disconnect();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!!
