Best JavaScript code snippet using cypress
defaultify.js
Source:defaultify.js
1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */4import utils from './ui/utils';5/**6 * Performs a deep scan and returns object without fields that are exactly the same as in default object7 * @param {Object} obj object that is supposed to be cleaned up8 * @param {Object} defaultObject an object representing the default object with default fields9 * @returns {Object} object with removed default fields10 */11export function defaultifyObject(obj, defaultObject) {12 if (!obj) {13 return null;14 }15 const resultingObject = {};16 let completeMatch = true;17 for (let field in obj) {18 if (obj.hasOwnProperty(field)) {19 let shouldCopy = true;20 let subDefObj = undefined;21 if (defaultObject.hasOwnProperty('*')) {22 // this means that all fields of the object should be checked23 // this is going to be applied for item.textSlots24 subDefObj = defaultObject['*'];25 } else if (defaultObject.hasOwnProperty(field)) {26 subDefObj = defaultObject[field];27 }28 if (typeof subDefObj !== 'undefined') {29 if (typeof obj[field] === typeof subDefObj) {30 if (Array.isArray(obj[field])) {31 resultingObject[field] = [];32 if (Array.isArray(subDefObj) && subDefObj.length === 1) {33 if (obj[field].length > 0) {34 // if there is at least one item in array - we should not let it be removed completelly 35 completeMatch = false;36 }37 for (let i = 0; i < obj[field].length; i++) {38 const nestedResult = defaultifyObject(obj[field][i], subDefObj[0]);39 if (typeof nestedResult !== 'undefined') {40 resultingObject[field][i] = nestedResult;41 } else {42 resultingObject[field][i] = {};43 }44 }45 shouldCopy = false;46 } else {47 shouldCopy = true;48 }49 } else if (typeof obj[field] === 'object') {50 const nestedResult = defaultifyObject(obj[field], subDefObj);51 if (typeof nestedResult !== 'undefined') {52 resultingObject[field] = nestedResult;53 shouldCopy = false;54 completeMatch = false;55 } else {56 shouldCopy = false;57 }58 } else if (obj[field] === subDefObj) {59 shouldCopy = false;60 }61 }62 }63 if (shouldCopy) {64 resultingObject[field] = obj[field];65 completeMatch = false;66 }67 }68 }69 70 if (completeMatch) {71 return undefined;72 }73 return resultingObject;74}75/**76 * Enriches object with defaults specified in another object.77 * It uses the same structure as 'defaultifyObject' function78 * @param {*} obj 79 * @param {*} defaultObj 80 */81export function enrichObjectWithDefaults(obj, defaultObj) {82 for (let field in defaultObj) {83 if (defaultObj.hasOwnProperty(field)) {84 if (field === '*') {85 for (let objField in obj) {86 enrichObjectWithDefaults(obj[objField], defaultObj['*']);87 }88 } else {89 const subDefObj = defaultObj[field]90 if (!obj.hasOwnProperty(field) 91 || obj[field] === null92 || typeof obj[field] !== typeof subDefObj 93 || (Array.isArray(subDefObj) && !Array.isArray(obj[field]))) {94 // in case they have different types - we should correct the object, otherwise it will be in broken state95 if (Array.isArray(subDefObj)) {96 obj[field] = [];97 } else {98 obj[field] = utils.clone(subDefObj);99 }100 } else {101 if (typeof subDefObj === 'object' && !Array.isArray(subDefObj)) {102 enrichObjectWithDefaults(obj[field], subDefObj);103 } else if (Array.isArray(subDefObj) && subDefObj.length === 1) {104 for (let i = 0; i < obj[field].length; i++) {105 // enriching each array element106 enrichObjectWithDefaults(obj[field][i], subDefObj[0]);107 }108 }109 }110 }111 }112 }113 return obj;...
test_copy-b-to-utag-data.js
Source:test_copy-b-to-utag-data.js
1// Declare global variables for Standard JS (linter)2/* global describe, it */3'use strict'4const chai = require('chai')5chai.use(require('chai-like'))6chai.use(require('dirty-chai')) // appease the linter7chai.use(require('deep-equal-in-any-order'))8const stringFunctions = require('../helpers/stringFunctions.js')9const code = stringFunctions.getVanillaJsFile('code/copy-b-to-utag-data.js')10// to share among tests11let exported12describe('the copy-to-utag-data extension', function () {13 it('should export without error', function () {14 const before = 'function theExtension (b, utag) {\n'15 const after = '\nreturn [b, utag && utag.data]\n}'16 exported = stringFunctions.exportNamedElements(code, ['theExtension'], before, after)17 chai.expect(exported).to.be.an('object').with.key('theExtension')18 })19 it('should work in a simple case without side-effects', function () {20 const b = {21 shouldCopy: 'to utag.data 1',22 shouldAlsoCopy: 'to utag.data 2'23 }24 const utag = {25 data: { 'cp.testCookie': 'testValue' }26 }27 const output = exported.theExtension(b, utag)28 const expectedB = {29 shouldCopy: 'to utag.data 1',30 shouldAlsoCopy: 'to utag.data 2'31 }32 const expectedUtagData = {33 shouldCopy: 'to utag.data 1',34 shouldAlsoCopy: 'to utag.data 2',35 'cp.testCookie': 'testValue'36 }37 chai.expect(output).to.deep.equal([expectedB, expectedUtagData])38 })39 it('should not do anything if b is undefined', function () {40 let b41 const utag = {42 data: { 'cp.testCookie': 'testValue' }43 }44 const output = exported.theExtension(b, utag)45 let expectedB46 const expectedUtagData = {47 'cp.testCookie': 'testValue'48 }49 chai.expect(output).to.deep.equal([expectedB, expectedUtagData])50 })51 it('should not do anything if utag is undefined', function () {52 const b = {53 shouldCopy: 'to utag.data 1',54 shouldAlsoCopy: 'to utag.data 2'55 }56 let utag57 const output = exported.theExtension(b, utag)58 const expectedB = {59 shouldCopy: 'to utag.data 1',60 shouldAlsoCopy: 'to utag.data 2'61 }62 let expectedUtagData63 chai.expect(output).to.deep.equal([expectedB, expectedUtagData])64 })65 it('should not do anything if utag.data is undefined', function () {66 const b = {67 shouldCopy: 'to utag.data 1',68 shouldAlsoCopy: 'to utag.data 2'69 }70 const utag = {}71 const output = exported.theExtension(b, utag)72 const expectedB = {73 shouldCopy: 'to utag.data 1',74 shouldAlsoCopy: 'to utag.data 2'75 }76 let expectedUtagData77 chai.expect(output).to.deep.equal([expectedB, expectedUtagData])78 })...
jsx-dom.js
Source:jsx-dom.js
1/* eslint-disable */2/* modified from create-element-x */3const isArray =4 Array.isArray ||5 (arg => Object.prototype.toString.call(arg) === "[object Array]");6const isHTMLCollection = arg =>7 Object.prototype.toString.call(arg) === "[object HTMLCollection]";8const isNodeList = arg =>9 Object.prototype.toString.call(arg) === "[object NodeList]";10const renameAttributes = {11 className: 'class',12 htmlFor: 'for',13}14export const createCreateElement = (createElement, createTextNode) => {15 return (tagName, attributes, ...children) => {16 const el = createElement(tagName);17 for (const attr in attributes) {18 if (attr.startsWith('__')) {19 //ignore debug props20 } else if (attr.startsWith('on')) {21 el[attr.toLowerCase()] = attributes[attr];22 } else {23 el.setAttribute(renameAttributes[attr] || attr, attributes[attr]);24 }25 }26 function appendChild(el, children) {27 if (children === null) return;28 let shouldCopy;29 if (30 isArray(children) ||31 (shouldCopy = isHTMLCollection(children)) ||32 (shouldCopy = isNodeList(children))33 ) {34 let cs = children;35 if (shouldCopy) {36 cs = Array.prototype.slice.call(cs, 0);37 }38 cs.forEach(item => appendChild(el, item));39 } else if (typeof children === "string" || typeof children === "number") {40 el.appendChild(createTextNode(`${children}`));41 } else {42 el.appendChild(children);43 }44 }45 appendChild(el, children);46 return el;47 };48};49export const createElement = createCreateElement(50 document.createElement.bind(document),51 document.createTextNode.bind(document)52);53const React = { createElement };54export default React;55export function render(callback) {56 return callback(React);...
copy-buffer-processor.js
Source:copy-buffer-processor.js
...5 constructor(options) {6 super();7 this.copyMode = options?.processorOptions?.copyMode ?? 'all';8 }9 get shouldCopy() {10 return this.copyMode === 'all' || this.copyMode === 'first';11 }12 addToBuffer(inputIndex, channelIndex, channelData) {13 const key = `${inputIndex}+${channelIndex}`;14 const buffer = this.buffers[key] ?? [];15 buffer.push(...Array.from(channelData));16 if (buffer.length >= bufferSize) {17 this.port.postMessage({ buffer: buffer, channelIndex, inputIndex });18 this.buffers[key] = [];19 if (this.copyMode === 'first') {20 this.copyMode = 'none';21 }22 } else {23 this.buffers[key] = buffer;...
build-plugins.js
Source:build-plugins.js
...32 let filesAndFolders = fs.readdirSync(fromPath)33 for (let file of filesAndFolders) {34 copyFolder(path.resolve(fromPath, file), path.resolve(toPath, file), shouldCopy)35 }36 } else if (shouldCopy(fromPath)) {37 copy(fromPath, toPath)38 }...
copyFiles.js
Source:copyFiles.js
1const path = require("path");2const fse = require("fs-extra");3const { promptOverwrites } = require("./promptOverwrites");4const copyFiles = async (destination, options) => {5 fse.ensureDirSync(destination);6 const { force, logger, events } = options;7 const sourcePath = path.join(__dirname, "initSource");8 const projectFiles = fse.readdirSync(sourcePath).filter(9 filename => !filename.endsWith(".eslintrc.json") //exclude .eslintrc.json10 );11 const destinationContents = fse.readdirSync(destination);12 const newContents = projectFiles.filter(13 filename => !destinationContents.includes(filename)14 );15 const contentCollisions = projectFiles.filter(filename =>16 destinationContents.includes(filename)17 );18 let shouldCopy;19 if (force) {20 shouldCopy = projectFiles;21 } else {22 const overwriteContents = await promptOverwrites(contentCollisions, logger);23 shouldCopy = [...newContents, ...overwriteContents];24 }25 await events.emit("init:copyingProjectFiles", {26 destinationPath: destination,27 });28 for (const file of shouldCopy) {29 fse.copySync(path.join(sourcePath, file), path.join(destination, file));30 }31};...
symlink.js
Source:symlink.js
1'use strict';2const path = require('path');3const shell = require('shelljs');4const actionPaths = require('../action-paths');5const symlinkOrCopy = (source, dest, topDir) => new Promise(6 (resolve, reject) => {7 const to = path.relative(path.dirname(dest), source);8 const shouldCopy = to.includes('node_modules') || path.relative(topDir, source).includes('..');9 const resultType = (10 shouldCopy11 ? 'file'12 : 'symlink'13 );14 const r = (15 shouldCopy16 ? shell.cp('-rnL', source, dest)17 : shell.ln('-s', to, dest)18 );19 return (20 r.code === 021 ? resolve(resultType)22 : reject(r.stderr)23 );24 }25);26const plopActionSymlink = (answers, config, plop) => {27 const paths = actionPaths(answers, config, plop);28 const dest = paths.dest(config.path);29 const source = paths.source(config.target);30 const prettyDest = paths.pretty(dest);31 const prettySource = paths.pretty(source);32 return symlinkOrCopy(source, dest, plop.getDestBasePath()).then(t => (33 t === 'symlink'34 ? `${prettyDest} -> ${prettySource}`35 : prettyDest36 ));37};...
copy-extension-files.js
Source:copy-extension-files.js
1const fs = require('fs')2const toCopy = ['background.js', 'inject.js', 'runtime.js']3const files = fs.readdirSync('./www').filter(file => file.endsWith('.js'))4files.forEach(file => {5 const shouldCopy = toCopy.find(toCopyFile => file.startsWith(`${toCopyFile.split('.')[0]}`))6 if (shouldCopy) {7 console.log('copying', `./www/${file}`, `./www/${shouldCopy}`)8 fs.copyFileSync(`./www/${file}`, `./www/${shouldCopy}`)9 }10})11const needle = `<link rel="icon" type="image/png" href="assets/icon/favicon.png"/>`12const css = `13<style>14 html {15 min-width: 500px;16 min-height: 888px;17 }18 ::-webkit-scrollbar {19 width: 0px;20 background: transparent;21 }22</style>23`24// Inject chrome extension specific CSS to make window bigger25const index = fs.readFileSync('./www/index.html', { encoding: 'utf-8' })26if (index.indexOf('::-webkit-scrollbar') < 0) {27 const indexWithCss = index.replace(needle, `${needle}\n${css}`)28 if (index === indexWithCss) {29 throw new Error('Could not inject extension css!')30 }31 fs.writeFileSync('./www/index.html', indexWithCss)...
Using AI Code Generation
1describe("My First Test", () => {2 it("Visits the Kitchen Sink", () => {3 cy.contains("type").click();4 cy.url().should("include", "/commands/actions");5 cy.get(".action-email")6 .should("have.value", "
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 .should('have.value', '
Using AI Code Generation
1describe('Cypress', () => {2 it('should copy the text', () => {3 cy.get('.action-email')4 .should('have.value', 'email')5 .type('newemail')6 .should('have.value', 'newemail');7 });8});
Using AI Code Generation
1Cypress.Blob.shouldCopy = function (value) {2 return false;3};4Cypress.Blob.shouldCopy = function (value) {5 return false;6};
Using AI Code Generation
1it('should copy the text of the element and assert it', () => {2 cy.get('input').shouldCopy('Hello World')3})4Cypress.Commands.add('shouldCopy', { prevSubject: 'element' }, (subject, expected) => {5 cy.wrap(subject).click()6 cy.wrap(subject).invoke('val').then((text) => {7 expect(text).to.equal(expected)8 })9})10it('should copy the text of the element and assert it', () => {11 cy.get('input').shouldCopy('Hello World')12})13Cypress.Commands.add('shouldCopy', { prevSubject: 'element' }, (subject, expected) => {14 cy.wrap(subject).click()15 cy.wrap(subject).invoke('val').then((text) => {16 expect(text).to.equal(expected)17 })18})19it('should copy the text of the element and assert it', () => {20 cy.get('input').shouldCopy('Hello World')21})22Cypress.Commands.add('shouldCopy', { prevSubject: 'element' }, (subject, expected) => {23 cy.wrap(subject).click()
Using AI Code Generation
1describe('Test', () => {2 it('should work', () => {3 cy.get('input').should('be.visible').should('have.attr', 'name', 'q')4 cy.get('input').should('be.visible').should('have.attr', 'title', 'Search')5 cy.get('input').should('be.visible').should('have.attr', 'aria-label', 'Search')6 cy.get('input').should('be.visible').should('have.attr', 'aria-haspopup', 'false')7 cy.get('input').should('be.visible').should('have.attr', 'maxlength', '2048')8 cy.get('input').should('be.visible').should('have.attr', 'tabindex', '1')9 cy.get('input').should('be.visible').should('have.attr', 'spellcheck', 'false')10 cy.get('input').should('be.visible').should('have.attr', 'aria-autocomplete', 'both')11 cy.get('input').should('be.visible').should('have.attr', 'aria-controls', 'tsf')12 cy.get('input').should('be.visible').should('have.attr', 'aria-activedescendant', 'sbse0')13 cy.get('input').should('be.visible').should('have.attr', 'autocomplete', 'off')14 cy.get('input').should('be.visible').should('have.attr', 'role', 'combobox')15 cy.get('input').should('be.visible').should('have.attr', 'aria-expanded', 'true')16 cy.get('input').should('be.visible').should('have.attr', 'aria-label', 'Search')17 cy.get('input').should('be.visible').should('have.attr', 'aria-haspopup', 'false')18 cy.get('input').should('be.visible').should('have.attr', 'aria-autocomplete', 'both')19 cy.get('input').should('be.visible').should('have.attr', 'aria-controls', 'tsf')20 cy.get('input').should('be.visible').should('have.attr', 'aria-activedescendant', 'sbse0')21 cy.get('input').should('be.visible').should('have.attr', 'aria-label', '
Using AI Code Generation
1if(!Cypress.shouldCopy()) {2 cy.log('Running in production, so not copying file to fixtures folder');3 cy.log('Cypress should copy file to fixtures folder');4 cy.task('copyFile', {src: 'cypress/fixtures/file.json', dest: 'cypress/fixtures/file.json'});5 cy.log('Cypress should copy file to fixtures folder');6}
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!!