Best JavaScript code snippet using wpt
name-scopes.js
Source:name-scopes.js  
...182//183// Returns a promise that resolves to an IndexedDB database. The caller should184// close the database.185function openDatabase(testCase, version) {186    return openNamedDatabase(testCase, databaseName(testCase), version);187}188// Opens an IndexedDB database without performing schema changes.189//190// The given version number must match the database's current version.191//192// Returns a promise that resolves to an IndexedDB database. The caller should193// close the database.194function openNamedDatabase(testCase, databaseName, version) {195    const request = indexedDB.open(databaseName, version);196    return promiseForRequest(testCase, request).then(database => {197        testCase.add_cleanup(() => {198            database.close();199        });200        return database;201    });202}203// The data in the 'books' object store records in the first example of the204// IndexedDB specification.205const BOOKS_RECORD_DATA = [206    { title: "Quarry Memories", author: "Fred", isbn: 123456 },207    { title: "Water Buffaloes", author: "Fred", isbn: 234567 },208    { title: "Bedrock Nights", author: "Barney", isbn: 345678 },209];210// Creates a 'books' object store whose contents closely resembles the first211// example in the IndexedDB specification.212const createBooksStore = (testCase, database) => {213    const store = database.createObjectStore("books", {214        keyPath: "isbn",215        autoIncrement: true,216    });217    store.createIndex("by_author", "author");218    store.createIndex("by_title", "title", { unique: true });219    for (let record of BOOKS_RECORD_DATA) store.put(record);220    return store;221};222// Creates a 'not_books' object store used to test renaming into existing or223// deleted store names.224function createNotBooksStore(testCase, database) {225    const store = database.createObjectStore("not_books");226    store.createIndex("not_by_author", "author");227    store.createIndex("not_by_title", "title", { unique: true });228    return store;229}230// Verifies that an object store's indexes match the indexes used to create the231// books store in the test database's version 1.232//233// The errorMessage is used if the assertions fail. It can state that the234// IndexedDB implementation being tested is incorrect, or that the testing code235// is using it incorrectly.236function checkStoreIndexes(testCase, store, errorMessage) {237    assert_array_equals(238        store.indexNames,239        ["by_author", "by_title"],240        errorMessage,241    );242    const authorIndex = store.index("by_author");243    const titleIndex = store.index("by_title");244    return Promise.all([245        checkAuthorIndexContents(testCase, authorIndex, errorMessage),246        checkTitleIndexContents(testCase, titleIndex, errorMessage),247    ]);248}249// Verifies that an object store's key generator is in the same state as the250// key generator created for the books store in the test database's version 1.251//252// The errorMessage is used if the assertions fail. It can state that the253// IndexedDB implementation being tested is incorrect, or that the testing code254// is using it incorrectly.255function checkStoreGenerator(testCase, store, expectedKey, errorMessage) {256    const request = store.put({257        title: "Bedrock Nights " + expectedKey,258        author: "Barney",259    });260    return promiseForRequest(testCase, request).then(result => {261        assert_equals(result, expectedKey, errorMessage);262    });263}264// Verifies that an object store's contents matches the contents used to create265// the books store in the test database's version 1.266//267// The errorMessage is used if the assertions fail. It can state that the268// IndexedDB implementation being tested is incorrect, or that the testing code269// is using it incorrectly.270function checkStoreContents(testCase, store, errorMessage) {271    const request = store.get(123456);272    return promiseForRequest(testCase, request).then(result => {273        assert_equals(result.isbn, BOOKS_RECORD_DATA[0].isbn, errorMessage);274        assert_equals(result.author, BOOKS_RECORD_DATA[0].author, errorMessage);275        assert_equals(result.title, BOOKS_RECORD_DATA[0].title, errorMessage);276    });277}278// Verifies that index matches the 'by_author' index used to create the279// by_author books store in the test database's version 1.280//281// The errorMessage is used if the assertions fail. It can state that the282// IndexedDB implementation being tested is incorrect, or that the testing code283// is using it incorrectly.284function checkAuthorIndexContents(testCase, index, errorMessage) {285    const request = index.get(BOOKS_RECORD_DATA[2].author);286    return promiseForRequest(testCase, request).then(result => {287        assert_equals(result.isbn, BOOKS_RECORD_DATA[2].isbn, errorMessage);288        assert_equals(result.title, BOOKS_RECORD_DATA[2].title, errorMessage);289    });290}291// Verifies that an index matches the 'by_title' index used to create the books292// store in the test database's version 1.293//294// The errorMessage is used if the assertions fail. It can state that the295// IndexedDB implementation being tested is incorrect, or that the testing code296// is using it incorrectly.297function checkTitleIndexContents(testCase, index, errorMessage) {298    const request = index.get(BOOKS_RECORD_DATA[2].title);299    return promiseForRequest(testCase, request).then(result => {300        assert_equals(result.isbn, BOOKS_RECORD_DATA[2].isbn, errorMessage);301        assert_equals(result.author, BOOKS_RECORD_DATA[2].author, errorMessage);302    });303}304// Returns an Uint8Array with pseudorandom data.305//306// The PRNG should be sufficient to defeat compression schemes, but it is not307// cryptographically strong.308function largeValue(size, seed) {309    const buffer = new Uint8Array(size);310    // 32-bit xorshift - the seed can't be zero311    let state = 1000 + seed;312    for (let i = 0; i < size; ++i) {313        state ^= state << 13;314        state ^= state >> 17;315        state ^= state << 5;316        buffer[i] = state & 0xff;317    }318    return buffer;319}320async function deleteAllDatabases(testCase) {321    const dbs_to_delete = await indexedDB.databases();322    for (const db_info of dbs_to_delete) {323        let request = indexedDB.deleteDatabase(db_info.name);324        let eventWatcher = requestWatcher(testCase, request);325        await eventWatcher.wait_for("success");326    }327}328// Keeps the passed transaction alive indefinitely (by making requests329// against the named store). Returns a function that asserts that the330// transaction has not already completed and then ends the request loop so that331// the transaction may autocommit and complete.332function keepAlive(testCase, transaction, storeName) {333    let completed = false;334    transaction.addEventListener("complete", () => {335        completed = true;336    });337    let keepSpinning = true;338    function spin() {339        if (!keepSpinning) return;340        transaction.objectStore(storeName).get(0).onsuccess = spin;341    }342    spin();343    return testCase.step_func(() => {344        assert_false(completed, "Transaction completed while kept alive");345        keepSpinning = false;346    });347}348// Return a promise that resolves after a setTimeout finishes to break up the349// scope of a function's execution.350function timeoutPromise(ms) {351    return new Promise(resolve => {352        setTimeout(resolve, ms);353    });354}355("use strict");356// Creates the structure inside a test database.357//358// The structure includes two stores with identical indexes and nearly-similar359// records. The records differ in the "path" attribute values, which are used to360// verify that IndexedDB returns the correct records when queried.361//362// databaseName appears redundant, but we don't want to rely on database.name.363const buildStores = (database, databaseName, useUniqueKeys) => {364    for (let storeName of ["x", "y"]) {365        const store = database.createObjectStore(storeName, {366            keyPath: "pKey",367            autoIncrement: true,368        });369        for (let indexName of ["x", "y"]) {370            store.createIndex(indexName, `${indexName}Key`, {371                unique: useUniqueKeys,372            });373        }374        for (let xKeyRoot of ["x", "y"]) {375            for (let yKeyRoot of ["x", "y"]) {376                let xKey, yKey;377                if (useUniqueKeys) {378                    xKey = `${xKeyRoot}${yKeyRoot}`;379                    yKey = `${yKeyRoot}${xKeyRoot}`;380                } else {381                    xKey = xKeyRoot;382                    yKey = yKeyRoot;383                }384                const path = `${databaseName}-${storeName}-${xKeyRoot}-${yKeyRoot}`;385                store.put({ xKey: xKey, yKey: yKey, path: path });386            }387        }388    }389};390// Creates two databases with identical structures.391const buildDatabases = (testCase, useUniqueKeys) => {392    return createNamedDatabase(testCase, "x", database =>393        buildStores(database, "x", useUniqueKeys),394    )395        .then(database => database.close())396        .then(() =>397            createNamedDatabase(testCase, "y", database =>398                buildStores(database, "y", useUniqueKeys),399            ),400        )401        .then(database => database.close());402};403// Reads all the store's values using an index.404//405// Returns a Promise that resolves with an array of values.406const readIndex = (testCase, index) => {407    return new Promise((resolve, reject) => {408        const results = [];409        const request = index.openCursor(IDBKeyRange.bound("a", "z"), "next");410        request.onsuccess = () => {411            const cursor = request.result;412            if (cursor) {413                results.push(cursor.value);414                cursor.continue();415            } else {416                resolve(results);417            }418        };419    });420};421// Verifies that a database contains the expected records.422const checkDatabaseContent = (423    testCase,424    database,425    databaseName,426    usedUniqueKeys,427) => {428    const promises = [];429    const transaction = database.transaction(["x", "y"], "readonly");430    for (let storeName of ["x", "y"]) {431        const store = transaction.objectStore(storeName);432        for (let indexName of ["x", "y"]) {433            const index = store.index(indexName);434            const promise = readIndex(testCase, index).then(results => {435                assert_array_equals(436                    results437                        .map(result => `${result.path}:${result.pKey}`)438                        .sort(),439                    [440                        `${databaseName}-${storeName}-x-x:1`,441                        `${databaseName}-${storeName}-x-y:2`,442                        `${databaseName}-${storeName}-y-x:3`,443                        `${databaseName}-${storeName}-y-y:4`,444                    ],445                    "The results should include all records put into the store",446                );447                let expectedKeys = usedUniqueKeys448                    ? ["xx:xx", "xy:yx", "yx:xy", "yy:yy"]449                    : ["x:x", "x:y", "y:x", "y:y"];450                assert_array_equals(451                    results452                        .map(result => `${result.xKey}:${result.yKey}`)453                        .sort(),454                    expectedKeys,455                    "The results should include all the index keys put in the store",456                );457                assert_array_equals(458                    results.map(result => result[`${indexName}Key`]),459                    results.map(result => result[`${indexName}Key`]).sort(),460                    "The results should be sorted by the index key",461                );462            });463            promises.push(promise);464        }465    }466    return Promise.all(promises).then(() => database);467};468promise_test(testCase => {469    return buildDatabases(testCase, false)470        .then(() => openNamedDatabase(testCase, "x", 1))471        .then(database => checkDatabaseContent(testCase, database, "x", false))472        .then(database => database.close())473        .then(() => openNamedDatabase(testCase, "y", 1))474        .then(database => checkDatabaseContent(testCase, database, "y", false))475        .then(database => database.close());476}, "Non-unique index keys");477promise_test(testCase => {478    return buildDatabases(testCase, true)479        .then(() => openNamedDatabase(testCase, "x", 1))480        .then(database => checkDatabaseContent(testCase, database, "x", true))481        .then(database => database.close())482        .then(() => openNamedDatabase(testCase, "y", 1))483        .then(database => checkDatabaseContent(testCase, database, "y", true))484        .then(database => database.close());...support-promises.js
Source:support-promises.js  
...129//130// Returns a promise that resolves to an IndexedDB database. The caller should131// close the database.132function openDatabase(testCase, version) {133  return openNamedDatabase(testCase, databaseName(testCase), version);134}135// Opens an IndexedDB database without performing schema changes.136//137// The given version number must match the database's current version.138//139// Returns a promise that resolves to an IndexedDB database. The caller should140// close the database.141function openNamedDatabase(testCase, databaseName, version) {142  const request = indexedDB.open(databaseName, version);143  const eventWatcher = requestWatcher(testCase, request);144  return eventWatcher.wait_for('success').then(() => {145    const database = request.result;146    testCase.add_cleanup(() => { database.close(); });147    return database;148  });149}150// The data in the 'books' object store records in the first example of the151// IndexedDB specification.152const BOOKS_RECORD_DATA = [153  { title: 'Quarry Memories', author: 'Fred', isbn: 123456 },154  { title: 'Water Buffaloes', author: 'Fred', isbn: 234567 },155  { title: 'Bedrock Nights', author: 'Barney', isbn: 345678 },...Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var db = wptoolkit.openNamedDatabase("testdb");3db.transaction(function (tx) {4    tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');5    tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');6    tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');7});Using AI Code Generation
1var wptouchPro = require('wptouch-pro');2var db = wptouchPro.openNamedDatabase('wptouch_pro');3db.transaction(function(tx) {4    tx.executeSql('SELECT * FROM wptouch_pro', [], function(tx, res) {5        console.log('number of rows: ' + res.rows.length);6        for (var i = 0; i < res.rows.length; i++) {7            console.log('row ' + i + ': ' + JSON.stringify(res.rows.item(i)));8        }9    });10});11var db = openDatabase('wptouch_pro', '1.0', 'WPtouch Pro Database', 2 * 1024 * 1024);12db.transaction(function(tx) {13    tx.executeSql('SELECT * FROM wptouch_pro', [], function(tx, res) {14        console.log('number of rows: ' + res.rows.length);15        for (var i = 0; i < res.rows.length; i++) {16            console.log('row ' + i + ': ' + JSON.stringify(res.rows.item(i)));17        }18    });19});Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var db = wptoolkit.openNamedDatabase('testdb', 'test.db', 1);3db.transaction(function(tx) {4    tx.executeSql('CREATE TABLE IF NOT EXISTS mytable (id unique, data)');5    tx.executeSql('INSERT INTO mytable (id, data) VALUES (1, "First row")');6    tx.executeSql('INSERT INTO mytable (id, data) VALUES (2, "Second row")');7});8db.transaction(function(tx) {9    tx.executeSql('SELECT * FROM mytable', [], function(tx, results) {10        var len = results.rows.length, i;11        for (i = 0; i < len; i++) {12            console.log(results.rows.item(i).data);13        }14    });15});16db.transaction(function(tx) {17    tx.executeSql('DROP TABLE mytable');18});Using AI Code Generation
1var wptools = require('./wptools.js');2var db = wptools.openNamedDatabase('test.db');3if (db == null) {4  console.log('Error opening database');5  process.exit(1);6}7var res = wptools.createTable(db, 'test1', ['id', 'name', 'age']);8if (res == false) {9  console.log('Error creating table');10  process.exit(1);11}12var res = wptools.insertRecord(db, 'test1', ['1', 'John', '29']);13if (res == false) {14  console.log('Error inserting record');15  process.exit(1);16}17var rec = wptools.getRecord(db, 'test1', 'id', '1');18if (rec == null) {19  console.log('Error getting record');20  process.exit(1);21}22console.log('Record: ' + rec);23var res = wptools.updateRecord(db, 'test1', 'id', '1', ['name', 'age'], ['Jim', '30']);24if (res == false) {25  console.log('Error updating record');26  process.exit(1);27}28var rec = wptools.getRecord(db, 'test1', 'id', '1');29if (rec == null) {30  console.log('Error getting record');31  process.exit(1);32}33console.log('Record: ' + rec);34var res = wptools.deleteRecord(db, 'test1', 'id', '1');35if (res == false) {36  console.log('Error deleting record');37  process.exit(1);38}39var rec = wptools.getRecord(db, 'test1', 'id', '1');40if (rec == null) {41  console.log('Error getting record');42  process.exit(1);43}44console.log('Record: ' + rec);Using AI Code Generation
1var db = openNamedDatabase("myDatabase", "myDatabase", 1024 * 1024);2db.transaction(function (tx) {3    tx.executeSql("CREATE TABLE IF NOT EXISTS myTable (id unique, data)");4    tx.executeSql("INSERT INTO myTable (id, data) VALUES (1, 'First row')");5    tx.executeSql("INSERT INTO myTable (id, data) VALUES (2, 'Second row')");6});7db.transaction(function (tx) {8    tx.executeSql("SELECT * FROM myTable", [], function (tx, result) {9        var len = result.rows.length, i;10        msg = "<p>Found rows: " + len + "</p>";11        document.querySelector('#status').innerHTML +=  msg;12        for (i = 0; i < len; i++){13            console.log("Row = " + i + " ID = " + result.rows.item(i).id + " Data =  " + result.rows.item(i).data);14        }15    });16});Using AI Code Generation
1const {wptoolkit} = require('wptoolkit');2wptoolkit.openNamedDatabase("mydb", function(error, db) {3    if (error) {4        console.log(error);5    } else {6        console.log("Database opened");7    }8});9const {wptoolkit} = require('wptoolkit');10wptoolkit.openDatabase("mydb", "1.0", function(error, db) {11    if (error) {12        console.log(error);13    } else {14        console.log("Database opened");15    }16});17const {wptoolkit} = require('wptoolkit');18wptoolkit.closeDatabase("mydb", "1.0", function(error, db) {19    if (error) {20        console.log(error);21    } else {22        console.log("Database closed");23    }24});25const {wptoolkit} = require('wptoolkit');26wptoolkit.deleteDatabase("mydb", "1.0", function(error, db)Using AI Code Generation
1var db = wptoolkit.openNamedDatabase("testdb", "1.0", "test db", 1000000);2db.transaction(function (tx) {3    tx.executeSql("CREATE TABLE IF NOT EXISTS testtable (id INTEGER PRIMARY KEY ASC, data TEXT, data_num NUMERIC)");4});5db.transaction(function (tx) {6    tx.executeSql("INSERT INTO testtable (data, data_num) VALUES (?,?)", ["test", 100], function (tx, res) {7        alert("insertId: " + res.insertId + " -- probably 1");8        alert("rowsAffected: " + res.rowsAffected + " -- should be 1");9    }, function (e) {10        alert("ERROR: " + e.message);11    });12});13db.transaction(function (tx) {14    tx.executeSql("SELECT * FROM testtable", [], function (tx, res) {15        alert("res.rows.length: " + res.rows.length + " -- should be 1");16        alert("res.rows.item(0).data: " + res.rows.item(0).data + " -- should be 'test'");17    }, function (e) {18        alert("ERROR: " + e.message);19    });20});21db.transaction(function (tx) {22    tx.executeSql("DELETE FROM testtable WHERE id=?", [1], function (tx, res) {23        alert("rowsAffected: " + res.rowsAffected + " -- should be 1");24    }, function (e) {25        alert("ERROR: " + e.message);26    });27});28db.transaction(function (tx) {29    tx.executeSql("DROP TABLE IF EXISTS testtable");30});31db.transaction(function (tx) {32    tx.executeSql("DROP DATABASE testdb");33});34db.close();35wptoolkit.deleteDatabase("testdb");Using AI Code Generation
1var db = window.openDatabase('wptouch_pro', 1, 'WPTouch Pro Database', 1024*1024);2var query = "SELECT * FROM settings WHERE setting_name = 'wptouch_pro_is_mobile_device'";3db.transaction(function (tx) {4    tx.executeSql(query, [], function (tx, results) {5        var len = results.rows.length, i;6        for (i = 0; i < len; i++) {7            alert(results.rows.item(i).setting_value);8        }9    }, null);10});11var db = window.openDatabase('wptouch_pro', 1, 'WPTouch Pro Database', 1024*1024);12var query = "SELECT * FROM settings WHERE setting_name = 'wptouch_pro_is_mobile_device'";13db.transaction(function (tx) {14    tx.executeSql(query, [], function (tx, results) {15        var len = results.rows.length, i;16        for (i = 0; i < len; i++) {17            alert(results.rows.item(i).setting_value);18        }19    }, null);20});21var db = window.openDatabase('wptouch_pro', 1, 'WPTouch Pro Database', 1024*1024);22var query = "SELECT * FROM settings WHERE setting_name = 'wptouch_pro_is_mobile_device'";23db.transaction(function (tx) {24    tx.executeSql(query, [], function (tx, results) {25        var len = results.rows.length, i;26        for (i = 0; i < len; i++) {27            alert(results.rows.item(i).setting_value);28        }29    }, null);30});31var db = window.openDatabase('wptouch_pro', 1, 'WPTouch Pro Database', 1024*1024);32var query = "SELECT * FROM settings WHERE setting_name = 'wptouch_pro_is_mobile_device'";33db.transaction(function (tx) {34    tx.executeSql(query, [], function (tx, results) {35        var len = results.rows.length, i;36        for (i = 0; i < len; i++) {37            alert(results.rowsLearn 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!!
