Best JavaScript code snippet using cypress
AddHouse.jsx
Source:AddHouse.jsx
1import React, {useContext, useEffect, useState} from 'react';2import {Button, makeStyles, Typography} from "@material-ui/core";3import {useForm, useWatch} from "react-hook-form";4import {yupResolver} from "@hookform/resolvers/yup";5import * as yup from "yup";6import FileInput from "../../common/Form/FileInput";7import MyInput from "../../common/Form/MyInput";8import TextArea from "../../common/Form/TextArea";9import Select from "../../common/Form/Select";10import AdminContext from "../AdminContext";11import ContentForm, {ContentSlide} from "../../common/Form/ContentForm";12const numberField = yup.number().required().positive();13const schema = yup.object().shape({14 title: yup.string()15 .required(),16 description: yup.string()17 .required(),18 totalArea: numberField,19 usableArea: numberField,20 dimensions1: numberField,21 dimensions2: numberField,22 minPrice: numberField,23 maxPrice: numberField,24 bathRooms:numberField,25 bedRooms: numberField,26});27const useStyles = makeStyles(theme => ({28 doubleInput: {29 display: 'flex',30 justifyContent: 'space-between',31 '& div': {32 width: '47%',33 }34 }35}))36const refactorDefValue = (defaultValues) => {37 let values = defaultValues && {38 imagesURL: defaultValues.imagesURL,39 title: defaultValues.title,40 usableArea: defaultValues.usableArea,41 totalArea: defaultValues.totalArea,42 dimensions1: defaultValues.dimensions[0],43 dimensions2: defaultValues.dimensions[1],44 floors: defaultValues.floors,45 minPrice: defaultValues.minPrice,46 maxPrice: defaultValues.maxPrice,47 bedRooms: defaultValues.bedRooms,48 bathRooms: defaultValues.bathRooms,49 description: defaultValues.description,50 };51 defaultValues?.includes.forEach((include, index) => values[`includes${index + 1}`] = include)52 return values;53}54const AddHouse = ({defaultValues, openCloseAdminDialogContent}) => {55 const {addHouse} = useContext(AdminContext);56 const styles = useStyles();57 const defaultFormValues = refactorDefValue(defaultValues);58 const {register, unregister, control, handleSubmit, formState: {errors}} = useForm({59 mode: 'onBlur',60 resolver: yupResolver(schema),61 defaultValues: defaultFormValues,62 });63 const description = useWatch({name: 'description', control});64 const [includesCount, setIncludesCount] = useState(defaultValues?.includes ? defaultValues.includes.length: 1);65 const [includes, setIncludes] = useState([]);66 useEffect(() => {67 const test = () => {68 let result = [];69 for (let i=1; i <= includesCount; i++) {70 result.push(<MyInput71 key={i}72 placeholder={`Ð ÑÑоимоÑÑÑ Ð²ÐºÐ»ÑÑено(${i})`}73 {...register(`includes${i}`)}74 />)75 }76 return result;77 }78 setIncludes(test())79 }, [includesCount])80 const onAddHouse = (data) => {81 addHouse(data, includesCount, defaultValues?.id);82 openCloseAdminDialogContent(false, null);83 }84 const deleteIncludeField = () => {85 unregister(`includes${includesCount}`)86 setIncludesCount(c => c - 1)87 }88 return (89 <ContentForm handleSubmit={handleSubmit} onSubmit={onAddHouse} buttonTitle={'ÐобавиÑÑ Ð´Ð¾Ð¼'} errors={errors}>90 <ContentSlide>91 <FileInput h={'250px'} control={control} name={'imagesURL'}/>92 </ContentSlide>93 <ContentSlide>94 <MyInput placeholder={'Ðазвание дома'} {...register('title')}/>95 <TextArea placeholder={'ÐпиÑание'} maxLength={5000} value={description} {...register('description')}/>96 </ContentSlide>97 <ContentSlide>98 <MyInput placeholder={'ÐбÑÐ°Ñ Ð¿Ð»Ð¾ÑадÑ'} {...register('totalArea')}/>99 <MyInput placeholder={'ÐÐ¾Ð»ÐµÐ·Ð½Ð°Ñ Ð¿Ð»Ð¾ÑадÑ'} {...register('usableArea')}/>100 <div className={styles.doubleInput}>101 <MyInput placeholder={'ÐабаÑиÑÑ(длина)'} {...register('dimensions1')}/>102 <MyInput placeholder={'ÐабаÑиÑÑ(ÑиÑина)'} {...register('dimensions2')}/>103 </div>104 <div className={styles.doubleInput}>105 <MyInput placeholder={'ÐинималÑÐ½Ð°Ñ Ñена'} {...register('minPrice')}/>106 <MyInput placeholder={'ÐакÑималÑÐ½Ð°Ñ Ñена'} {...register('maxPrice')}/>107 </div>108 </ContentSlide>109 <ContentSlide>110 <MyInput placeholder={'ÐолиÑеÑÑво Ñ/Ñзлов'} {...register('bathRooms')}/>111 <MyInput placeholder={'ÐолиÑеÑÑво Ñпален'} {...register('bedRooms')}/>112 <Select defaultValue={'1'} {...register('floors')}>113 <option disabled>ÐолиÑеÑÑво ÑÑажей</option>114 <option value={'1'}>1</option>115 <option value={'1.5'}>1.5</option>116 <option value={'2'}>2</option>117 </Select>118 </ContentSlide>119 <ContentSlide>120 <div style={{height: '100%', maxHeight: '250px', overflowY: 'auto'}}>121 <Typography variant={'subtitle1'}>ÐÑÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð´Ð¾Ð»Ð¶Ð½Ñ Ð±ÑÑÑ Ð²Ð¸Ð´Ð°: "Ðаголовок@ ...Ñело..."</Typography>122 <Typography variant={'subtitle1'}>ÐÑе, ÑÑо до "@" бÑде имеÑÑ ÑÑолÑеннÑй ÑÑиÑÑ; вÑе, ÑÑо поÑле - обÑÑнÑй.</Typography>123 {includes}124 <div>125 <Button onClick={() => setIncludesCount(c => c + 1)}>+</Button>126 <Button onClick={deleteIncludeField}>-</Button>127 </div>128 </div>129 </ContentSlide>130 </ContentForm>131 );132};...
fileprocessor.js
Source:fileprocessor.js
1// Copyright 2019 Google LLC2//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//7// https://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14'use strict';15global.__commandName = 'test';16const assert = require('assert');17const glob = require("glob");18const { IDLError } = require('../errors.js');19const { FileProcessor } = require('../fileprocessor.js');20const ACTUAL_IDL_FILES = 'idl/**/**/**/*.idl';21const TEST_IDL_FILES = './test/files/';22global.__Flags = require('../flags.js').FlagStatus('./test/files/exp_flags.json5');23describe('FileProcessor', () => {24 describe('process()', () => {25 it('Confirms that interface structures can be interpreted in all IDL files', () => {26 const foundFiles = glob.sync(ACTUAL_IDL_FILES);27 let foundErr ='';28 foundFiles.forEach((f) => {29 if (f.includes('testing/')) { return; }30 try {31 const fp = new FileProcessor(f);32 fp.process((result) => {33 // result not needed for this test.34 });35 } catch (err) {36 foundErr = err;37 console.log(err.message)38 }39 });40 assert.ok(!(foundErr instanceof IDLError));41 })42 it('Confirms that the four interface data objects are in the resulting fileset', () => {43 const testFile = `${TEST_IDL_FILES}multiple-structures.idl`;44 const fp = new FileProcessor(testFile);45 let interfaceNames = [];46 fp.process((result) => {47 interfaceNames.push(result.name);48 });49 let msg = `Found interfaces are: ${interfaceNames}.`50 assert.strictEqual(interfaceNames.length, 4);51 });52 it('Confirms that standard interfaces are read', () => {53 const testFile = `${TEST_IDL_FILES}burnable.idl`;54 const fp = new FileProcessor(testFile);55 let iface;56 fp.process((result) => {57 iface = result;58 });59 assert.strictEqual(iface.name, 'Burnable');60 });61 it('Confirms that callback interfaces are read', () => {62 const testFile = `${TEST_IDL_FILES}interface-callback.idl`;63 const fp = new FileProcessor(testFile);64 let iface;65 fp.process((result) => {66 iface = result;67 });68 assert.strictEqual(iface.name, 'InterfaceCallback');69 });70 it('Confirms that callback functions are read', () => {71 const testFile = `${TEST_IDL_FILES}callback.idl`;72 const fp = new FileProcessor(testFile);73 let iface;74 fp.process((result) => {75 if (result.type === 'callback') {76 iface = result;77 }78 });79 assert.strictEqual(iface.name, 'DecodeErrorCallback');80 });81 it('Confirms that dictionaries are read', () => {82 const testFile = `${TEST_IDL_FILES}dictionary.idl`;83 const fp = new FileProcessor(testFile);84 let iface;85 fp.process((result) => {86 if (result.type === 'dictionary') {87 iface = result;88 }89 });90 assert.strictEqual(iface.name, 'USBDeviceFilter');91 });92 it('Confirms that a single enum is read', () => {93 const testFile = `${TEST_IDL_FILES}enum.idl`;94 const fp = new FileProcessor(testFile);95 let iface;96 fp.process((result) => {97 if (result.type === 'enum') {98 iface = result;99 }100 });101 assert.strictEqual(iface.name, `AudioContextState`);102 });103 it('Confirms that multiple enums are read from a single file', () => {104 const testFile = `${TEST_IDL_FILES}enums.idl`;105 const fp = new FileProcessor(testFile);106 let iface = 0;107 fp.process((result) => {108 iface++;109 });110 assert.strictEqual(iface, 2);111 });112 it('Confirms that identifiers containing "enum" are ignored', () => {113 const testFile = `${TEST_IDL_FILES}alternate-key.idl`;114 const fp = new FileProcessor(testFile);115 assert.doesNotThrow(() => {116 fp.process((result) => {117 // result not needed for this test.118 });119 }, IDLError);120 });121 it('Confirms that mixin interfaces are read', () => {122 const testFile = `${TEST_IDL_FILES}mixin.idl`;123 const fp = new FileProcessor(testFile);124 let iface;125 fp.process((result) => {126 iface = result;127 });128 assert.strictEqual(iface.name, 'Body');129 });130 it('Confirms that includes statements are read', () => {131 const testFile = `${TEST_IDL_FILES}mixin-includes.idl`;132 const fp = new FileProcessor(testFile);133 fp.process((result) => {134 if (result.type === 'includes') {135 assert.ok(result.type === 'includes');136 }137 });138 });139 it('Confirms that multiple includes statements are read', () => {140 const testFile = `${TEST_IDL_FILES}mixin-includes-multiple.idl`;141 const fp = new FileProcessor(testFile);142 let includesCount = 0;143 fp.process((result) => {144 if (result.type === 'includes') {145 includesCount++;146 }147 });148 assert.strictEqual(includesCount, 2);149 })150 it('Confirms that partial interfaces are read', () => {151 const testFile = `${TEST_IDL_FILES}interface-partial.idl`;152 const fp = new FileProcessor(testFile);153 let iface;154 fp.process((result) => {155 iface = result;156 });157 assert.strictEqual(iface.name, 'InterfacePartial');158 });159 it('Confirms that simple named getters are processed as methods', () => {160 const testFile = `${TEST_IDL_FILES}getters-simple-named-only.idl`;161 const fp = new FileProcessor(testFile);162 let found;163 fp.process(result => {164 found = result.getters.find(g => {165 return g.type === 'method';Â 166 });167 });168 assert.strictEqual(found.name, 'getItem');169 });170 it('Confirms that complex named getters are processed as methods', () => {171 });172 });...
contentScript.js
Source:contentScript.js
1$(document).ready(function () {2 var title = document.title;3 var url = window.location.href;4 // constants5 var ACTION_START = 'ACTION_START';6 var ACTION_STOP = 'ACTION_STOP';7 var ACTION_MUTE = 'ACTION_MUTE';8 var NOTIFICATION = 'NOTIFICATION';9 var GET_TASKS = 'GET_TASKS';10 // flags11 var mute = false;12 var task = null;13 function sendNotification(text, once) {14 if (!task) return;15 chrome.runtime.sendMessage({16 type: NOTIFICATION,17 data: text ? text : (task ? task.notification : '')18 });19 if (once) return;20 var it = setInterval(function () {21 if (mute) {22 clearInterval(it);23 return;24 }25 chrome.runtime.sendMessage({26 type: NOTIFICATION,27 data: text ? text : (task ? task.notification : '')28 });29 }, 3000);30 }31 var delay = 1000;32 function clickButtons(clickArray) {33 if (!clickArray.length) return;34 var $buttons = $('button:visible, input[type="button"]:visible');35 clickArray.forEach(function (text) {36 $buttons.each(function () {37 var $button = $(this);38 text = text || '';39 text = text.toLowerCase();40 if ($button.text().toLowerCase() === text) {41 setTimeout(function () {42 $button.click();43 }, delay);44 delay += 1000;45 }46 });47 });48 }49 function check() {50 if (!task) return;51 clickButtons(task.clickBefore);52 setTimeout(function () { // wait till before buttons are clicked.53 var pageVisibleContent = $('*:not(:has(*)):visible').text().toLowerCase();54 var notify = false;55 // check includes56 var includesCount = 0;57 task.includes.forEach(function (include) {58 include = include || '';59 include = include.toLowerCase();60 if (pageVisibleContent.indexOf(include) !== -1) {61 includesCount++;62 }63 });64 // check excludes65 var excludesCount = 0;66 task.excludes.forEach(function (exclude) {67 exclude = exclude || '';68 exclude = exclude.toLowerCase();69 if (pageVisibleContent.indexOf(exclude) === -1) {70 excludesCount++;71 }72 });73 if (includesCount > 0 || excludesCount > 0) {74 if (includesCount === task.includes.length && excludesCount === task.excludes.length) {75 notify = true;76 }77 }78 if (notify) {79 sendNotification();80 clickButtons(task.clickAfter);81 return;82 }83 // refresh84 setTimeout(function () {85 location.reload();86 }, (task.clickBefore.length + task.clickAfter.length) * 1000);87 }, task.clickBefore.length * 1200);88 }89 chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {90 switch (message.type) {91 case ACTION_START:92 mute = false;93 task = JSON.parse(message.data);94 break;95 case ACTION_STOP:96 task = null;97 mute = true;98 break;99 case ACTION_MUTE:100 mute = true;101 break;102 default:103 break;104 }105 });106 chrome.runtime.sendMessage({107 type: GET_TASKS108 }, function (message) {109 var tasks = message.data;110 var activeTabId = message.tabId;111 task = tasks[activeTabId];112 mute = false;113 if (task) {114 // check url changes115 if (task.url === url) {116 setTimeout(function () {117 check();118 }, task.interval * 1000);119 } else {120 if (task.lockUrl && task.started) {121 sendNotification('Your url changed. Please stop extension.');122 }123 }124 }125 });126 window.onunload = function () {127 };...
AdminContext.js
Source:AdminContext.js
1import React from "react";2import {toNumber} from "../../utils/helpers";3import {commonAPI, deleteImg} from "../../firebase/api";4import {firestoreCollections} from "../../utils/consts";5export const addHouse = async (data, includesCount, docId) => {6 const files = data.imagesURL;7 const dataCopy = {8 title: data.title,9 usableArea: toNumber(data.usableArea),10 totalArea: toNumber(data.totalArea),11 dimensions: [toNumber(data.dimensions1), toNumber(data.dimensions2)],12 floors: data.floors,13 minPrice: toNumber(data.minPrice),14 maxPrice: toNumber(data.maxPrice),15 bedRooms: toNumber(data.bedRooms),16 bathRooms: toNumber(data.bathRooms),17 description: data.description,18 }19 const includes = [];20 for (let i = 1; i <= includesCount; i++) {21 const includeName = `includes${i}`;22 const include = data[includeName];23 includes.push(include)24 }25 dataCopy.includes = includes;26 await commonAPI.addUpdateDoc(firestoreCollections.houses, files, dataCopy, docId)27}28export const addNewsItem = async (data, docId) => {29 const files = data.imagesURL;30 delete data.imagesURL;31 await commonAPI.addUpdateDoc(firestoreCollections.news, files, data, docId)32}33const getArrayFromFiles = (files) => {34 let filesArray = [];35 for (const file of files) {36 filesArray.push(file);37 }38 return filesArray;39}40export const addBannerItem = async (files) => {41 const validateFiles = getArrayFromFiles(files);42 await commonAPI.addUpdateDoc(firestoreCollections.banners, validateFiles, {})43}44export const addNewAlbum = async (name) => {45 await commonAPI.addUpdateDoc(firestoreCollections.albums, [], {name})46}47export const addPhotosToAlbum = async (albumId, files, data) => {48 const validateFiles = getArrayFromFiles(files);49 await commonAPI.addUpdateDoc(firestoreCollections.albums, validateFiles, data, albumId);50}51export const deletePhotosFromAlbum = async (albumId, imageURL, oldData) => {52 const imagesURLWithoutDeleted = oldData.imagesURL?.filter(img => img !== imageURL);53 await addPhotosToAlbum(albumId, [], {...oldData, imagesURL: imagesURLWithoutDeleted})54 await deleteImg(imageURL);55}...
useDataQuery.js
Source:useDataQuery.js
1import { useEffect, useState } from 'react'2import * as A from '@core/arena'3import { Query } from '@common/model/query'4import { useOnUpdate } from '@webapp/components/hooks'5import { useActions } from './actions'6const defaults = {7 [Query.displayTypes.table]: { limit: 15, offset: 0 },8}9export const useDataQuery = ({ query, limitData = true }) => {10 const defaultValues = defaults[Query.getDisplayType(query)]11 const initialLimit = limitData ? defaultValues.limit : null12 const [data, setData] = useState(null)13 const [count, setCount] = useState(null)14 const [limit, setLimit] = useState(initialLimit)15 const [offset, setOffset] = useState(defaultValues.offset)16 const hasSelection = Query.hasSelection(query)17 const mode = Query.getMode(query)18 const dataEmpty = data ? A.isEmpty(data.data) : true19 const dataLoaded = data ? data.loaded && hasSelection : false20 const dataLoading = data ? data.loading : false21 const entityDefUuid = Query.getEntityDefUuid(query)22 const attributeDefUuids = Query.getAttributeDefUuids(query)23 const dimensions = Query.getDimensions(query)24 const measures = Query.getMeasures(query)25 const measuresAggregateFnsSize = Array.from(measures.values()).flat().length26 const filter = Query.getFilter(query)27 const filterRecordUuid = Query.getFilterRecordUuid(query)28 const sort = Query.getSort(query)29 const Actions = useActions({ setData, setCount })30 // on entity def uuid or filter update: reset data31 useOnUpdate(Actions.reset, [entityDefUuid, filter])32 // on mount or on update offset, attributeDefUuids, dimensions, measures: fetch or reset33 useEffect(() => {34 if (hasSelection) Actions.fetch({ offset, limit, query, includesCount: !dataLoaded })35 else Actions.reset()36 }, [limit, offset, attributeDefUuids, dimensions, measures, measuresAggregateFnsSize, mode, sort])37 // on filter update: fetch data and count38 useOnUpdate(() => {39 if (hasSelection) Actions.fetch({ offset, limit, query, includesCount: true })40 }, [filter, filterRecordUuid])41 return {42 count: count && count.data,43 data: data && data.data,44 dataEmpty,45 dataLoaded,46 dataLoading,47 limit,48 offset,49 setLimit,50 setOffset,51 setData: (dataUpdated) => setData({ ...data, data: dataUpdated }),52 }...
cloudQuery.js
Source:cloudQuery.js
1import Moralis from "moralis";2import { useEffect, useState } from "react";3const defaultCloudQueryOptions = {4 includesCount: false,5 countName: "count",6 params: {},7 postProcess: (r) => r.attributes,8 onSuccess: () => {},9};10export function useMoralisCloudQuery(11 methodName,12 options = defaultCloudQueryOptions13) {14 const [state, setState] = useState({15 data: null,16 error: null,17 loading: false,18 });19 useEffect(() => {20 if (methodName) {21 setState((v) => ({ ...v, loading: true }));22 console.log("useMoralisCloudQuery:: methodName:", methodName," options:", options);23 Moralis.Cloud.run(methodName, options.params)24 .then((data) => {25 console.log("useMoralisCloudQuery:: data:", data);26 if (data) {27 let output = {};28 if (options.includesCount) {29 output.results = options.postProcess30 ? data.results.map(options.postProcess)31 : data.results;32 output[options.countName] = data[options.countName];33 } else {34 output = options.postProcess35 ? data.map(options.postProcess)36 : data;37 }38 console.log("useMoralisCloudQuery:: output:", output);39 setState({ data: output, error: null, loading: false });40 } else {41 setState({ data: null, error: null, loading: false });42 }43 if (typeof options.onSuccess === "function") {44 options.onSuccess();45 }46 })47 .catch((error) => {48 console.error(error);49 setState({ data: null, error, loading: false });50 });51 }52 }, [methodName, options]);53 return state;...
index.js
Source:index.js
1/**2 * trimSymbols - removes consecutive identical symbols if they quantity bigger that size3 * @param {string} string - the initial string4 * @param {number} size - the allowed size of consecutive identical symbols5 * @returns {string} - the new string without extra symbols according passed size6 */7export function trimSymbols(string, size) {8 let includesCount = 0;9 let formattedString = '';10 if (size === 0 || !string) {11 return '';12 }13 if (!size) {14 return string;15 }16 for (let i=0; i < string.length; i++) {17 if (string[i] === string[i+1]) {18 includesCount++;19 } else {20 includesCount = 0;21 }22 if (includesCount < size) {23 formattedString+=string[i];24 }25 }26 return formattedString;...
07-Search-For-A-Number.js
Source:07-Search-For-A-Number.js
1function searchForANumber(array, info) {2 let countToTake = info[0];3 let countToDelete = info[1];4 let elementToSearch = info[2];5 let result = array.slice(0, (countToTake));6 result = result.slice(countToDelete);7 let includesCount = 0;8 for (let element of result) {9 if (element == elementToSearch) {10 includesCount++;11 }12 }13 console.log(`Number ${elementToSearch} occurs ${includesCount} times.`);14}...
Using AI Code Generation
1describe('My First Test', function() {2 it('Visits the Kitchen Sink', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe("My First Test", () => {2 it("Does not do much!", () => {3 cy.contains("type").click();4 cy.url().should("include", "/commands/actions");5 cy.get(".action-email")6 .type("
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!