Best JavaScript code snippet using ava
manualTestEvents.js
Source:manualTestEvents.js
1/*2 * Copyright (C) 2013 salesforce.com, inc.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 */16function manualTestEvents() {17 var ACTIONS = ["fetch", "reload", "clearCache"];18 var ACTIONS_WEIGHT = [0.7, 0.2, 0.1]; // must add up to 119 var DEFS = ["ui:scroller", "ui:tree", "ui:carousel", "auraStorageTest:manualTesterBigCmp"];20 var DEFAULT_DELAY_MS = 1;21 var DEFAULT_MAX_DELAY = 1000;22 // WIP - capture repros that are know to cause issues23 var PRESET_INDEX = -1;24 var PRESET1 = ["ui:scroller", "ui:carousel", "reload", "ui:scroller", "ui:carousel", "reload", "ui:scroller", "ui:carousel", "reload", "ui:scroller", "ui:carousel", "reload", "ui:scroller", "ui:carousel","reload", "ui:scroller", "ui:carousel","clearCache", "reload"];25 /**26 * Gets the amount of time in milliseconds to delay before running an event.27 * @param {Boolean} randomDelay true to get a random amount of delay, otherwise the default will be returned28 */29 function getDelay(randomDelay) {30 return !!randomDelay ? getRandomDelay() : DEFAULT_DELAY_MS;31 };32 /**33 * Gets a random amount of time in milliseconds to delay before running an event.34 * @param {Integer} maxMs the maximum milliseconds possible to return35 */36 function getRandomDelay(maxMs) {37 maxMs = !!maxMs ? maxMs : DEFAULT_MAX_DELAY;38 return Math.floor(Math.random() * maxMs);39 };40 /**41 * Returns a random item from a list, given weights for each item. 42 * For example, if [a,b,c] were passed in with weights [.1,.2,.7], a would have a 10% chance of being chosen43 * and c a 70% chance.44 * @param {Array} list the items to choose from45 * @param {Array} weight the list of weights that must add up to 1, where each index of the array maps to the index of the list46 */47 function getRandomItem(list, weight) {48 var sum = weight.reduce(function(a,b) { return (a + b) }, 0);49 $A.assert(sum > .9999 && sum < 1.0001, "sum of weights must be 1");50 var randomNumber = Math.random();51 var weightedSum = 0;52 for (var i = 0; i < list.length; i++) {53 weightedSum += weight[i];54 weightedSum = +weightedSum.toFixed(2);55 if (randomNumber <= weightedSum) {56 return list[i];57 }58 }59 };60 /**61 * Returns an event to execute.62 * @param {String} action the name of the event to run63 * @param {Integer} delay the amount of time in milliseconds to delay before executing the event64 * @param {String} def the def to fetch for a 'fetch' event65 */66 function buildEvent(action, delay, def) {67 var event = {68 "action": action,69 "delay": delay70 };71 if (def) {72 event["def"] = def;73 }74 return event;75 };76 return {77 /**78 * Returns a random event79 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing80 */81 getRandomEvent: function(randomDelay) {82 var action = getRandomItem(ACTIONS, ACTIONS_WEIGHT);83 if (action === "fetch") {84 return this.getRandomFetchEvent(randomDelay);85 } else {86 return buildEvent(action, getDelay(randomDelay));87 }88 },89 /**90 * Returns an event that fetches a component from the server, choosing a def from the list at random.91 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing92 */93 getRandomFetchEvent: function(randomDelay) {94 var defIndex = Math.floor(Math.random() * (DEFS.length));95 return buildEvent("fetch", getDelay(randomDelay), DEFS[defIndex]);96 },97 /**98 * Returns an event that fetches the given def from the server99 * @param {String} def the name of the def to fetch from the server100 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing101 */102 getFetchEvent: function(def, randomDelay) {103 return buildEvent("fetch", getDelay(randomDelay), def);104 },105 /**106 * Returns a reload event.107 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing108 */109 getReloadEvent: function(randomDelay) {110 return buildEvent("reload", getDelay(randomDelay));111 },112 /**113 * Returns an event that clears the cache.114 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing115 */116 getClearCacheEvent: function(randomDelay) {117 return buildEvent("clearCache", getDelay(randomDelay));118 },119 /**120 * For a reset list of events to execute, returns the next event in the list.121 * @param {Boolean} randomDelay true to delay the action a random amount of time before executing122 */123 getNextPresetEvent: function(randomDelay) {124 PRESET_INDEX = ++PRESET_INDEX >= PRESET1.length ? 0 : PRESET_INDEX;125 var event = PRESET1[PRESET_INDEX];126 if (event === "reload") {127 return this.getReloadEvent(randomDelay);128 } else if (event === "clearCache") {129 return this.getClearCacheEvent(randomDelay);130 } else {131 return this.getFetchEvent(event, randomDelay);132 }133 }134 };...
index.js
Source:index.js
1import { add, remove, complete, generateRandomDelay } from "../utils";2 /**3 * This function returns a list of todos stored in the localstorage4 */5export const fetchTodos = () => {6 return new Promise((resolve, reject) => {7 const data = JSON.parse(localStorage.getItem('todo_store'));8 const randomDelay = generateRandomDelay();9 if(data){10 return setTimeout(() => resolve(data.todos), randomDelay)11 }12 return setTimeout(() => reject("Oops! Store not available.", randomDelay));13 })14}15/**16 * Saves a todo to the localstorage and returns it if successful17 * @param {*} todo 18 */19export const saveTodo = todo => {20 return new Promise((resolve, reject) => {21 /**22 * Ordinarily, the logic of checking the todos count should not live here but for testing purposes, 23 * I am limiting the number of Incomplete Todos to be added to 3.24 * This should enable reject to be fired after adding 3 incomplete todos25 */26 const data = JSON.parse(localStorage.getItem('todo_store'))27 const randomDelay = generateRandomDelay();28 if(data.todos){29 const newData = {...data, todos: add(data.todos, todo)}30 localStorage.setItem('todo_store', JSON.stringify(newData))31 return setTimeout(() => resolve(todo), randomDelay)32 }33 return setTimeout(() => reject("Memory full. Delete some incomplete todos to add more."), randomDelay)34 })35}36/**37 * Removes a todo from the localstorage and returns the id if successful38 * @param {*} id 39 */40export const removeTodo = id => {41 return new Promise((resolve, reject) => {42 const randomDelay = generateRandomDelay();43 // TODO We could make this more robust by checking if it's a valid id44 // and returning a corresponding error message45 if(id){46 const data = JSON.parse(localStorage.getItem('todo_store'))47 const newData = {...data, todos: remove(data.todos, id)}48 49 localStorage.setItem('todo_store', JSON.stringify(newData))50 51 return setTimeout(() => resolve(id), randomDelay)52 }53 return setTimeout(() => reject("Please select a todo to remove"), randomDelay)54 })55}56/**57 * Marks a todo as complete and returns the id if successful58 * @param {*} id 59 */60export const completeTodo = id => {61 return new Promise((resolve, reject) => {62 const randomDelay = generateRandomDelay();63 if(id){64 const data = JSON.parse(localStorage.getItem('todo_store'))65 const newData = {...data, todos: complete(data.todos, id)}66 localStorage.setItem('todo_store', JSON.stringify(newData))67 return setTimeout(() => resolve(id), randomDelay)68 }69 return setTimeout(() => reject("Please select a todo to mark as complete"), randomDelay)70 })...
BackgroundForms.js
Source:BackgroundForms.js
...29 <div className={classes.background}>30 <Circle31 left={randomPosition()}32 size={randomSize()}33 delay={randomDelay()}34 />35 <Circle36 left={randomPosition()}37 size={randomSize()}38 delay={randomDelay()}39 />40 <Circle41 left={randomPosition()}42 size={randomSize()}43 delay={randomDelay()}44 />45 <Circle46 left={randomPosition()}47 size={randomSize()}48 delay={randomDelay()}49 />50 <Circle51 left={randomPosition()}52 size={randomSize()}53 delay={randomDelay()}54 />55 <Circle56 left={randomPosition()}57 size={randomSize()}58 delay={randomDelay()}59 />60 <Circle61 left={randomPosition()}62 size={randomSize()}63 delay={randomDelay()}64 />65 <Circle66 left={randomPosition()}67 size={randomSize()}68 delay={randomDelay()}69 />70 <Circle71 left={randomPosition()}72 size={randomSize()}73 delay={randomDelay()}74 />75 <Circle76 left={randomPosition()}77 size={randomSize()}78 delay={randomDelay()}79 />80 <Circle81 left={randomPosition()}82 size={randomSize()}83 delay={randomDelay()}84 />85 <Circle86 left={randomPosition()}87 size={randomSize()}88 delay={randomDelay()}89 />90 <Circle91 left={randomPosition()}92 size={randomSize()}93 delay={randomDelay()}94 />95 <Circle96 left={randomPosition()}97 size={randomSize()}98 delay={randomDelay()}99 />100 <Circle101 left={randomPosition()}102 size={randomSize()}103 delay={randomDelay()}104 />105 <Circle106 left={randomPosition()}107 size={randomSize()}108 delay={randomDelay()}109 />110 </div>111 );112};113BackgroundForms.propTypes = {114 styles: PropTypes.object,115};...
pseudoAPI.ts
Source:pseudoAPI.ts
...3 setTimeout(resolve, randomIntBetween(500, 3000));4 });5};6export const getWeather = async (zipCode: string) => {7 await randomDelay();8 if (!getWeatherCache[zipCode]) {9 getWeatherCache[zipCode] = randomIntBetween(5, 35);10 } else {11 getWeatherCache[zipCode] += randomIntBetween(-1, 2);12 }13 return getWeatherCache[zipCode];14};15const getWeatherCache: Record<string, number> = {};16function randomIntBetween(min: number, max: number) {17 return Math.floor(Math.random() * (max - min + 1) + min);18}19type ItemType = {20 label: string;21 checked: boolean;22};23class ShoppingListAPI {24 items: Record<number, ItemType>;25 constructor() {26 const persisted = localStorage.getItem("ShoppingListAPI");27 if (persisted == null) {28 this.items = {};29 } else {30 this.items = JSON.parse(persisted);31 }32 }33 async getItems() {34 await this.randomDelay("getItems");35 return this.items;36 }37 async getItem(id: number): Promise<ItemType | undefined> {38 await this.randomDelay("getItem", id);39 return this.items[id];40 }41 async createOrUpdateItem(id: number, item: ItemType) {42 await this.randomDelay("createOrUpdateItem", id);43 this.items[id] = item;44 this.persist();45 }46 async deleteItem(id: number) {47 await this.randomDelay("deleteItem", id);48 delete this.items[id];49 this.persist();50 }51 private async randomDelay(name: string, param?: number) {52 let label = `Fake Request: ${name}.`;53 if (param != null) label += ` id: ${param}`;54 await randomDelay();55 console.log(`End ${label}`);56 }57 private persist() {58 localStorage.setItem("ShoppingListAPI", JSON.stringify(this.items));59 }60}...
Using AI Code Generation
1var randomDelay = require('random-delay');2var delay = randomDelay(1000, 2000);3console.log(delay);4var randomDelay = require('random-delay');5var delay = randomDelay(1000, 2000, 100);6console.log(delay);7var randomDelay = require('random-delay');8var delay = randomDelay(1000, 2000, 100, 1000);9console.log(delay);10var randomDelay = require('random-delay');11var delay = randomDelay(1000, 2000, 100, 1000, 2000);12console.log(delay);13var randomDelay = require('random-delay');14var delay = randomDelay(1000, 2000, 100, 1000, 2000, 100);15console.log(delay);16var randomDelay = require('random-delay');17var delay = randomDelay(1000, 2000, 100, 1000, 2000, 100, 100);18console.log(delay);19var randomDelay = require('random-delay');20var delay = randomDelay(1000, 2000, 100, 1000, 2000, 100, 100, 200);21console.log(delay);22var randomDelay = require('random-delay');23var delay = randomDelay(1000, 2000, 100, 1000, 2000, 100, 100, 200, 50);24console.log(delay);25var randomDelay = require('random-delay');26var delay = randomDelay(1000, 2000, 100, 1000, 2000, 100, 100, 200, 50, 10);27console.log(delay);
Using AI Code Generation
1var available = require('./available.js');2console.log(available.randomDelay());3module.exports = {4 randomDelay: function() {5 return Math.random() * 10000;6 }7};8var available = require('./available.js');9console.log(available.randomDelay());10module.exports = {11 randomDelay: function() {12 return Math.random() * 10000;13 }14};15var available = require('./available.js');16console.log(available.randomDelay());17module.exports = {18 randomDelay: function() {19 return Math.random() * 10000;20 }21};22var available = require('./available.js');23console.log(available.randomDelay());24module.exports = {25 randomDelay: function() {26 return Math.random() * 10000;27 }28};29var available = require('./available.js');30console.log(available.randomDelay());31module.exports = {32 randomDelay: function() {33 return Math.random() * 10000;34 }35};36var available = require('./available.js');37console.log(available.randomDelay());38module.exports = {39 randomDelay: function() {40 return Math.random() * 10000;41 }42};43var available = require('./available.js');44console.log(available.randomDelay());45module.exports = {46 randomDelay: function() {47 return Math.random() * 10000;48 }49};
Using AI Code Generation
1var available = require('./available.js');2available.randomDelay(function() {3 console.log('Done!');4});5module.exports.randomDelay = function(callback) {6 var delay = Math.floor((Math.random() * 1000) + 500);7 setTimeout(callback, delay);8};
Using AI Code Generation
1var randomDelay = require('random-delay');2var randomDelay = require('random-delay');3randomDelay(1000, 2000, function(){4 console.log('This is a random delay between 1 and 2 seconds');5});6var randomDelay = require('random-delay');7randomDelay(1000, 2000, function(){8 console.log('This is a random delay between 1 and 2 seconds');9});10var randomDelay = require('random-delay');11randomDelay(1000, 2000, function(){12 console.log('This is a random delay between 1 and 2 seconds');13});14var randomDelay = require('random-delay');15randomDelay(1000, 2000, function(){16 console.log('This is a random delay between 1 and 2 seconds');17});18var randomDelay = require('random-delay');19randomDelay(1000, 2000, function(){20 console.log('This is a random delay between 1 and 2 seconds');21});22var randomDelay = require('random-delay');23randomDelay(1000, 2000, function(){24 console.log('This is a random delay between 1 and 2 seconds');25});26var randomDelay = require('random-delay');27randomDelay(1000, 2000, function(){28 console.log('This is a random delay between 1 and 2 seconds');29});30var randomDelay = require('random-delay');31randomDelay(1000, 2000, function(){32 console.log('This is a random delay between 1 and 2 seconds');33});34var randomDelay = require('random-delay');35randomDelay(1000, 2000, function(){36 console.log('This is a random delay between 1 and 2 seconds');37});
Using AI Code Generation
1var availableDelay = require('./availableDelay');2var delay = new availableDelay();3delay.randomDelay(1000, 3000, function(){4 console.log('I am delayed');5});6var availableDelay = function(){7 this.randomDelay = function(min, max, callback){8 var delay = Math.floor( Math.random() * (max - min + 1) ) + min;9 setTimeout(callback, delay);10 }11}12module.exports = availableDelay;13var availableDelay = require('./availableDelay');14var delay = new availableDelay();15delay.randomDelay(1000, 3000, function(){16 console.log('I am delayed');17});18var availableDelay = function(){19 this.randomDelay = function(min, max, callback){20 var delay = Math.floor( Math.random() * (max - min + 1) ) + min;21 setTimeout(callback, delay);22 }23}24module.exports = availableDelay;
Using AI Code Generation
1var randomDelay = require('random-delay');2var delay = randomDelay({min: 1000, max: 2000});3delay.then(function(){4 console.log('done');5});6randomDelay({min: 1000, max: 2000}).then(function(){7 console.log('done');8});9randomDelay({min: 1000, max: 2000}, function(){10 console.log('done');11});12randomDelay({min: 1000, max: 2000}, function(err){13 if(err){14 console.log('error', err);15 }else{16 console.log('done');17 }18});19randomDelay({min: 1000, max: 2000}, function(err, result){20 if(err){21 console.log('error', err);22 }else{23 console.log('done');24 }25});26randomDelay({min: 1000, max: 2000}, function(err, result){27 if(err){28 console.log('error', err);29 }else{30 console.log('done');31 }32});33randomDelay({min: 1000, max: 2000}, function(err, result){34 if(err){35 console.log('error', err);36 }else{37 console.log('done');38 }39});40randomDelay({min: 1000, max: 2000}, function(err, result){41 if(err){42 console.log('error', err);43 }else{44 console.log('done');45 }46});47randomDelay({min: 1000, max: 2000}, function(err, result){48 if(err){49 console.log('error', err);50 }else{51 console.log('done');52 }53});54randomDelay({min: 1000, max: 2000}, function(err, result){55 if(err){56 console.log('error', err);57 }else{58 console.log('done');59 }60});61randomDelay({min: 1000, max: 2000}, function(err, result){62 if(err){63 console.log('error', err);64 }else{65 console.log('done');66 }67});68randomDelay({min: 1000, max: 2000}, function(err, result
Using AI Code Generation
1var availableMethods = require('./availableMethods.js');2var randomDelay = availableMethods.randomDelay;3randomDelay(function() {4 console.log('randomDelay function callback called');5});6module.exports.randomDelay = function(callback) {7 setTimeout(callback, Math.floor(Math.random() * 1000));8};9exports.randomDelay = function(callback) {10 setTimeout(callback, Math.floor(Math.random() * 1000));11};12exports.randomDelay = function(callback) {13 setTimeout(callback, Math.floor(Math.random() * 1000));14};15exports.randomDelay2 = function(callback) {16 setTimeout(callback, Math.floor(Math.random() * 1000));17};18exports.randomDelay3 = function(callback) {19 setTimeout(callback, Math.floor(Math.random() * 1000));20};
Using AI Code Generation
1var test = require('./availableMethods');2var randomDelay = test.randomDelay;3randomDelay(function(){4 console.log("Hello after 4 to 8 seconds");5});6module.exports = {7 randomDelay: function(callback){8 var delay = Math.round((Math.random() * 4000) + 4000);9 setTimeout(callback, delay);10 }11};12var test = require('./availableMethods');13var randomDelay = test.randomDelay;
Using AI Code Generation
1var availableServices = require('./available-services');2var availableServices = new availableServices();3availableServices.randomDelay(1000, 2000, function(){4 console.log('Random delay has been completed');5});6var availableServices = function(){};7availableServices.prototype.randomDelay = function(min, max, callback){8 var randomTime = Math.floor(Math.random() * (max - min + 1)) + min;9 setTimeout(function(){10 callback();11 }, randomTime);12}13module.exports = availableServices;
Using AI Code Generation
1var availableFunctions = require('./availableFunctions.js');2availableFunctions.randomDelay(function(){3 console.log('hello world');4}, 0, 5000);5module.exports.randomDelay = function(callback, min, max){6 var delay = Math.floor(Math.random() * (max - min + 1)) + min;7 setTimeout(callback, delay);8};
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!!