Best JavaScript code snippet using cavy
search.js
Source:search.js  
...75      .then(response => {76        // On success, update the global state and return the stoplist.77        batch(() => {78          dispatch(updateStopwords(response.data.stopwords));79          dispatch(clearAsync());80        });81        return response.data.stopwords82      })83      .catch(error => {84        // On error, update the error log.85        batch(() => {86          dispatch(registerError(error));87          dispatch(clearAsync());88        });89      });90    }91  }92}93/**94 * Kick off a search by sending parameters to the REST API.95 * 96 * @param {Object} source Source text metadata.97 * @param {Object} target Target text metadata.98 * @param {Object} params Advanced options for the search.99 * @param {String[]} stopwords List of tokens to exclude from the search.100 * @param {boolean} pending True if any AJAX calls are in progress.101 * @returns {function} Callback that calls dispatch to handle communication.102 */103export function initiateSearch(source, target, params, stopwords, asyncReady) {104  return dispatch => {105    // Only kick off a request to the REST API if no other requests are active.106    if (asyncReady) {107      // Update app state to show there is a new async action.108      batch(() => {109        dispatch(updateSearchID());110        dispatch(updateResults());111        dispatch(updateSearchInProgress(true));112        dispatch(initiateAsync());113      });114      // Start a request to the parallels endpoint of the REST API.115      // This creates a Promise that resolves when a reqponse or error is received.116      axios({117          method: 'post',118          url: `${REST_API}/parallels/`,119          crossDomain: true,120          headers: {121            contentType: 'x-www-form-urlencoded',122            'X-Requested-With': 'XMLHttpRequest'123          },124          responseType: 'json',125          cacheControl: 'no-store',126          data : {127            method: {128              name: 'original',129              feature: params.feature,130              stopwords: stopwords,131              freq_basis: params.frequencyBasis,132              max_distance: parseInt(params.maxDistance, 10),133              distance_basis: params.distanceBasis,134              score_basis: params.scoreBasis135            },136            page_number: 0,137            per_page: 100,138            sort_by: 'score',139            sort_order: 'descending',140            source: {141              object_id: source.object_id,142              units: params.unitType143            },144            target: {145              object_id: target.object_id,146              units: params.unitType147            },148          }      149      })150      .catch(data => data.response)151      .then(response => {152        // On success, update the global state and return the search ID or results.153        let searchID = [];154        if (response.headers.location !== undefined) {155          searchID = response.headers.location.match(/parallels[/]([\w\d]+)/);156        }157        else if (response.request.responseURL !== undefined) {158          searchID = response.request.responseURL.match(/parallels[/]([\w\d]+)/);159        }160        161        batch(() => {162          dispatch(clearAsync());163          if (searchID.length > 1 && searchID[1] !== '') {164            dispatch(updateSearchID(searchID[1]));165          }166        });167        return searchID[1];168      })169      .catch(error => {170        // On error, update the error log.171        batch(() => {172          dispatch(clearAsync());173          dispatch(registerError(error));174        });175      });176    }177  }178}179/**180 * Ping the REST API to get the status of a search.181 * 182 * @param {String} searchID The ID of the search obained when it was initiated.183 * @param {boolean} pending True if any AJAX calls are in progress.184 * @returns {function} Callback that calls dispatch to handle communication.185 */186export function getSearchStatus(searchID, asyncReady) {187  return dispatch => {188    // Only kick off a request to the REST API if no other requests are active.189    if (asyncReady) {190      // Update app state to show there is a new async action.191      dispatch(initiateAsync());192      // Start a request to the parallels endpoint of the REST API.193      // This creates a Promise that resolves when a reqponse or error is received.194      axios({195        method: 'get',196        url: `${REST_API}/parallels/${searchID}/status/`,197        crossDomain: true,198        responseType: 'json',199        cacheControl: 'no-store'200      })201      .then(response => {202        // On success, update the global state and return the status.203        batch(() => {204          dispatch(clearAsync());205          if (response.data.status !== undefined) {206            dispatch(updateSearchStatus(response.data.status, response.data.progress));207          }208        });209        return response.data.status;210      })211      .catch(error => {212        // On error, update the error log.213        batch(() => {214          dispatch(clearAsync());215          dispatch(registerError(error));216        });217      })218    }219  }220}221/**222 * Fetch available search results from the REST API.223 * 224 * @param {String} searchID The ID of the search obained when it was initiated.225 * @param {boolean} asyncReady True if the app is ready to send a request.226 * @param {number} currentPage The page of results to fetch.227 * @param {number} rowsPerPage The number of rows to fetch.228 * @param {String} sortLabel The table header to sort by.229 * @param {number} sortOrder 1 (asc) or -1 (desc)230 * @returns {function} Callback that calls dispatch to handle communication.231 */232export function fetchResults(searchID, asyncReady, currentPage = 0,233                             rowsPerPage = 100, sortLabel = 'score',234                             sortOrder = -1) {235  return dispatch => {236    // Only kick off a request to the REST API if no other requests are active.237    if (asyncReady) {238      // Update app state to show there is a new async action.239      dispatch(initiateAsync());240      // Start a request to the parallels endpoint of the REST API.241      // This creates a Promise that resolves when a reqponse or error is received.242      axios({243          method: 'get',244          url: `${REST_API}/parallels/${searchID}`,245          crossDomain: true,246          responseType: 'json',247          cacheControl: 'no-store',248          params: {249            page_number: currentPage,250            per_page: rowsPerPage,251            sort_by: sortLabel,252            sort_order: sortOrder === -1 ? 'descending' : 'ascending',253          }254      })255      .then(response => {256        // On success, update the global state and return the results.257        // Because of strange design constraints and group consensus, normalize258        // all scores to be in range [0, 10].259        const maxScore = response.data.max_score;260        const nResults = response.data.total_count;261        const normedParallels = normalizeScores(response.data.parallels,262                                                maxScore >= 10 ? maxScore : 10);263        batch(() => {264          dispatch(clearAsync());265          dispatch(updateResults(normedParallels, nResults));266          dispatch(updateSearchInProgress(false));267        });268        269        return normedParallels;270      })271      .catch(error => {272        // On error, update the error log.273        batch(() => {274          dispatch(clearAsync());275          dispatch(registerError(error));276        });277      });278    }279  }...corpus.js
Source:corpus.js  
...64          language = languages.length > 0 ? languages[0] : '';65        }66        batch(() => {67          dispatch(updateAvailableLanguages(languages, language));68          dispatch(clearAsync());69        });70        return languages;71      })72      .catch(error => {73        // On error, update the error log.74        batch(() => {75          dispatch(registerError(error));76          dispatch(clearAsync());77        });78      });79    }80  };81}82/**83 * Update the selected language of the app.84 * 85 * @param {String} language The language to change to.86 * @returns {function} Callback that calls dispatch to update state.87 */88export function updateLanguage(language) {89  return dispatch => {90      batch(() => {91        dispatch(updateSelectedLanguage(language));92        dispatch(resetSearch());93      });94  }95}96/**97 * Fetch available texts of the selected language from the REST API.98 * 99 * @param {String} language The language of texts to fetch.100 * @param {boolean} shouldFetch True if a language was selected and no AJAX calls are in progress.101 * @returns {function} Callback that calls dispatch to handle communication.102 */103export function fetchTexts(language, shouldFetch) {104  return dispatch => {105    // Only kick off a request to the REST API if no other requests are active.106    if (shouldFetch) {107      // Update app state to show there is a new async action.108      dispatch(initiateAsync());109      // Start a request to the texts endpoint of the REST API.110      // This creates a Promise that resolves when a reqponse or error is received.111      axios({112        method: 'get',113        url: `${REST_API}/texts/`,114        crossDomain: true,115        responseType: 'json',116        params: {117          language: language.toLowerCase()118        }119      })120      .then(response => {121        // On success, update the global state and return the text list.122        const texts = response.data.texts.sort((a, b) => {123          return a.author > b.author || (a.author === b.author && a.title > b.title);124        });125        batch(() => {126          dispatch(updateAvailableTexts(texts));127          let source = undefined;128          let target = undefined;129          if (language.toLowerCase() === 'latin') {130            source = find(texts, {author: 'vergil', title: 'aeneid'});131            target = find(texts, {author: 'lucan', title: 'bellum civile'});132          }133          else if (language.toLowerCase() === 'greek') {134          }135          dispatch(updateSourceText(!isUndefined(source) ? source : texts[0]));136          dispatch(updateTargetText(!isUndefined(target) ? target : texts[-1]));137          dispatch(clearAsync())138        });139        return texts;140      })141      .catch(error => {142        // On error, update the error log.143        batch(() => {144          dispatch(registerError(error));145          dispatch(clearAsync());146        });147      });148    }149  };150}151export function fetchFullText(textID, unit, asyncReady) {152  return dispatch => {153    if (asyncReady) {154      console.log('fetching the full text');155      dispatch(initiateAsync());156      axios({157        method: 'get',158        url: `${REST_API}/units/`,159        crossDomain: true,160        responseType: 'json',161        params: {162          unit_type: unit,163          works: textID,164        }165      })166      .then(response => {167        console.log('response', response)168        batch(() => {169          const units = sortBy(response.data.units, 'index');170          dispatch(addFullText(textID, units));171          dispatch(clearAsync());172        });173        return response.data.units;174      })175      .catch(error => {176        // On error, update the error log.177        batch(() => {178          dispatch(registerError(error));179          dispatch(clearAsync());180        });181      });182    }183  };184}185export function ingestText(tessFile, metadata) {186  return dispatch => {187    dispatch(initiateAsync());188    let data = FormData();189    data.set('metadata', metadata);190    data.set('file', tessFile);191    axios({192      method: 'post',193      url: `${REST_API}/texts/`,194      crossDomain: true,195      responseType: 'json',196      headers: {197        'Content-Type': 'multipart/form'198      },199      data: data200    }).then(response => {201    }).error(error => {202      // On error, update the error log.203      batch(() => {204        dispatch(registerError(error));205        dispatch(clearAsync());206      });207    });208  };209}210export function updateTextMetadata(textID, metadata) {211  return dispatch => {212    axios({213      method: 'patch',214      url: `${REST_API}/texts/${textID}/`,215      crossDomain: true,216      responseType: 'json',217      data: metadata218    }).then(response => {219    }).error(error => {220      // On error, update the error log.221      batch(() => {222        dispatch(registerError(error));223        dispatch(clearAsync());224      });225    });226  };227}228export function deleteTexts(textIDs) {229  return dispatch => {230    textIDs.map(item =>231      axios({232        method: 'delete',233        url: `${REST_API}/texts/${item.object_id}/`,234        crossDomain: true,235        responseType: 'json',236      }).then(response => {237        238      }).error(error => {239        // On error, update the error log.240        batch(() => {241          dispatch(registerError(error));242          dispatch(clearAsync());243        });244      })245    );246  };...useSpinButton.ts
Source:useSpinButton.ts  
...52  const formatMessage = useMessageFormatter(intlMessages);53  const clearAsync = () => clearTimeout(_async.current);54  // eslint-disable-next-line arrow-body-style55  useEffect(() => {56    return () => clearAsync();57  }, []);58  let onKeyDown = (e) => {59    if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || isReadOnly) {60      return;61    }62    switch (e.key) {63      case "PageUp":64        if (onIncrementPage) {65          e.preventDefault();66          onIncrementPage();67          break;68        }69      // fallthrough!70      case "ArrowUp":71      case "Up":72        if (onIncrement) {73          e.preventDefault();74          onIncrement();75        }76        break;77      case "PageDown":78        if (onDecrementPage) {79          e.preventDefault();80          onDecrementPage();81          break;82        }83      // fallthrough84      case "ArrowDown":85      case "Down":86        if (onDecrement) {87          e.preventDefault();88          onDecrement();89        }90        break;91      case "Home":92        if (onDecrementToMin) {93          e.preventDefault();94          onDecrementToMin();95        }96        break;97      case "End":98        if (onIncrementToMax) {99          e.preventDefault();100          onIncrementToMax();101        }102        break;103    }104  };105  let isFocused = useRef(false);106  let onFocus = () => {107    isFocused.current = true;108  };109  let onBlur = () => {110    isFocused.current = false;111  };112  // Replace Unicode hyphen-minus (U+002D) with minus sign (U+2212).113  // This ensures that macOS VoiceOver announces it as "minus" even with other characters between the minus sign114  // and the number (e.g. currency symbol). Otherwise it announces nothing because it assumes the character is a hyphen.115  // In addition, replace the empty string with the word "Empty" so that iOS VoiceOver does not read "50%" for an empty field.116  textValue = textValue === "" ? formatMessage("Empty") : (textValue || `${value}`).replace("-", "\u2212");117  useEffect(() => {118    if (isFocused.current) {119      announce(textValue, "assertive");120    }121  }, [textValue]);122  const onIncrementPressStart = useCallback(123    (initialStepDelay: number) => {124      clearAsync();125      onIncrement();126      // Start spinning after initial delay127      _async.current = window.setTimeout(128        () => {129          if (isNaN(maxValue) || isNaN(value) || value < maxValue) {130            onIncrementPressStart(60);131          }132        },133        initialStepDelay134      );135    },136    [onIncrement, maxValue, value]137  );138  const onDecrementPressStart = useCallback(139    (initialStepDelay: number) => {140      clearAsync();141      onDecrement();142      // Start spinning after initial delay143      _async.current = window.setTimeout(144        () => {145          if (isNaN(minValue) || isNaN(value) || value > minValue) {146            onDecrementPressStart(60);147          }148        },149        initialStepDelay150      );151    },152    [onDecrement, minValue, value]153  );154  return {...Using AI Code Generation
1import { clearAsync } from 'cavy';2clearAsync();3import { testHook } from 'cavy';4testHook('testHookId');5import { wrap } from 'cavy';6wrap();7import { generateTestHook } from 'cavy';8generateTestHook('testHookId');9import { SpecReporter } from 'cavy';10SpecReporter();11import { TestHookStore } from 'cavy';12TestHookStore();13import { Tester } from 'cavy';14Tester();15import { withHook } from 'cavy';16withHook();17import { withHooks } from 'cavy';18withHooks();19import { withNavigationHelpers } from 'cavy';20withNavigationHelpers();21import { withNavigation } from 'cavy';22withNavigation();23import { withTestHook } from 'cavy';24withTestHook();25import { withTestHooks } from 'cavy';26withTestHooks();27import { withTestHookStore } from 'cavy';28withTestHookStore();29import { withTestHookStore } from 'cavy';Using AI Code Generation
1const { clearAsync } = require('cavy');2describe('Test', () => {3  it('should clear async storage', async () => {4    await clearAsync();5  });6});Using AI Code Generation
1it('Clears the input field', async () => {2  await this.clearAsync('input');3});4it('Presses the button', async () => {5  await this.pressAsync('button');6});7it('Types text', async () => {8  await this.typeTextAsync('input', 'Hello, world!');9});10it('Waits', async () => {11  await this.wait(1000);12});13it('Waits until', async () => {14  await this.waitUntil(async () => {15    const text = await this.getTextAsync('input');16    return text === 'Hello, world!';17  });18});19it('Waits', async () => {20  await this.wait(1000);21});22it('Waits until', async () => {23  await this.waitUntil(async () => {24    const text = await this.getTextAsync('input');25    return text === 'Hello, world!';26  });27});28it('Waits', async () => {29  await this.wait(1000);30});31it('Waits until', async () => {32  await this.waitUntil(async () => {33    const text = await this.getTextAsync('input');34    return text === 'Hello, world!';35  });36});37it('Waits', async () => {38  await this.wait(1000);39});Using AI Code Generation
1import { clearAsync } from 'cavy';2### `clearAsync()`3### `clearAsyncStorage()`4### `fillIn(textInputRef, text)`5### `tap(text)`6### `tapNth(nth, text)`7### `tapById(id)`8### `tapNthById(nth, id)`9### `tapByLabel(label)`10### `tapNthByLabel(nth, label)`11### `tapByTestId(testId)`12### `tapNthByTestId(nth, testId)`13### `tapByType(type)`14### `tapNthByType(nth, type)`15### `tapByProps(props)`16### `tapNthByProps(nth, props)`17### `tapByRef(ref)`18### `tapNthByRef(nth, ref)`19### `longPress(text)`20### `longPressNth(nth, text)`21### `longPressById(id)`22### `longPressNthById(nth, id)`23### `longPressByLabel(label)`24### `longPressNthByLabel(nth, label)`25### `longPressByTestId(testIdLearn 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!!
