Best JavaScript code snippet using cypress
download-image.js
Source: download-image.js
1// The modules2const urlp = require("url");3const http = require("http");4const https = require("https");5const path = require("path");6const fs = require("fs");7const sharp = require("sharp");8// The src9const storeErr = require("./store-err");10const request = require("./request");11// The dirs12const __TMPDIR = `${__dirname}/../temp/icons`;13const __OUTDIR = `${__dirname}/../../server/public/auto/icons`;14// The function15function icon (url, cb) {16 let siteType = getSiteType(url);17 if(siteType === "http") {18 let request = http.get(url, function (res) {19 let body = "";20 // Sets the enctype to binary21 res.setEncoding("binary");22 // Handles the data23 res.on("data", function (chunk) {24 body += chunk;25 });26 // Handles the end27 res.on("end", function () {28 let filename = getIconFileName(url);29 let outfile = `${filename.substring(0, filename.length - 4)}.jpg`;30 fs.writeFile(path.resolve(`${__TMPDIR}/${filename}`), body, "binary", function(err) {31 processIcon(filename, outfile).then(function () {32 cb(null, outfile);33 }).catch(function (err) {34 cb(err, null);35 });36 });37 });38 }).on("error", function (error) {39 request.abort();40 storeErr.appendFile(error);41 cb(error, null);42 }).on("timeout", function () {43 request.abort();44 cb(new Error("Timeout in request."), null);45 });46 } else if(siteType === "https") {47 let request = https.get(url, function (res) {48 let body = "";49 // Sets the enctype to binary50 res.setEncoding("binary");51 // Handles the data52 res.on("data", function (chunk) {53 body += chunk;54 });55 // Handles the end56 res.on("end", function () {57 let filename = getIconFileName(url);58 let outfile = `${filename.substring(0, filename.length - 4)}.jpg`;59 fs.writeFile(path.resolve(`${__TMPDIR}/${filename}`), body, "binary", function(err) {60 processIcon(filename, outfile).then(function () {61 cb(null, outfile);62 }).catch(function (err) {63 cb(err, null);64 });65 });66 });67 }).on("error", function (error) {68 request.abort();69 storeErr.appendFile(error);70 cb(error, null);71 }).on("timeout", function () {72 request.abort();73 cb(new Error("Timeout in request."), null);74 });75 } else {76 cb(new Error("Invalid file type"), null);77 }78}79// The url type function80function getSiteType(url) {81 if(url) {82 if (url.includes("https://")) {83 return "https";84 } else if (url.includes("http://")) {85 return "http"86 } else {87 return "none"88 }89 } else {90 return "none";91 }92}93// Processes the file94async function processIcon(filename, output, cb) {95 await sharp(path.resolve(`${__TMPDIR}/${filename}`))96 .resize(20, 20)97 .toFile(path.resolve(`${__OUTDIR}/${output}`))98 await fs.unlinkSync(path.resolve(`${__TMPDIR}/${filename}`));99}100// Gets the file name101function getIconFileName (url) {102 let urld = urlp.parse(url, true);103 let before = `${urld.protocol}//${urld.hostname}${urld.pathname}`;104 // Gets the extension105 if(before.substring(before.length, before.length - 4) === ".jpg") {106 return `${urld.hostname.split(".").join("-")}-${Date.now()}.jpg`;107 } else if(before.substring(before.length, before.length - 4) === ".png") {108 return `${urld.hostname.split(".").join("-")}-${Date.now()}.png`;109 } else if(before.substring(before.length, before.length - 4) === ".gif") {110 return `${urld.hostname.split(".").join("-")}-${Date.now()}.gif`;111 }else if(before.substring(before.length, before.length - 4) === ".ico") {112 return `${urld.hostname.split(".").join("-")}-${Date.now()}.ico`;113 }114}115// Exports...
index.js
Source: index.js
...40 if (BUNDLE) {41 return Promise.reject(new Error("Cannot process data URI in bundle-mode"));42 }43 const readIconProcess = new Promise((resolve, reject) => {44 const iconFilename = getIconFilename(domain, opts);45 fs.readFile(iconFilename, (err, buff) => {46 if (err) {47 return reject(err);48 }49 resolve(buff);50 });51 });52 return readIconProcess.then(iconData => encodeDataURI(iconData, "image/png"));53}54/**55 * @typedef {Object} IconDetails56 * @property {String} filename The full path of the icon file57 * @property {Boolean} isDefault Whether the icon is the default icon or not58 */59/**60 * Get icon details for a domain61 * @param {String|null} domain The domain to get icon details for. Pass null or undefined62 * to automatically fetch the default icon63 * @param {IconOptions=} param1 Options for getting the icon64 * @returns {IconDetails} Icon details65 * @memberof module:Iconographer66 */67function getIconDetails(domain, { greyscale = false } = {}) {68 const { domains, match } = require("../resources/index.json");69 const domainKey = domain ? findMatchingDomain(domain, Object.keys(domains), match) : domain;70 let filename,71 isDefault = !(domainKey && domains[domainKey]);72 if (!isDefault) {73 const { filename: imageFilename, filenameGreyscale: imageFilenameGrey } = domains[domainKey];74 filename = greyscale ? imageFilenameGrey : imageFilename;75 } else {76 filename = greyscale ? "default.grey.png" : "default.png";77 }78 filename = BUNDLE ? path.join("dist/images", filename) : path.resolve(__dirname, "../resources/images/", filename);79 return {80 filename,81 isDefault82 };83}84/**85 * Get the filename of an icon for a domain86 * @param {String} domain The domain87 * @param {IconOptions=} opts Options for getting the icon88 * @returns {String} The icon filename89 * @memberof module:Iconographer90 */91function getIconFilename(domain, opts) {92 return getIconDetails(domain, opts).filename;93}94/**95 * Return the path to the resources directory96 * @returns {String} The path97 * @memberof module:Iconographer98 */99function getResourcesPath() {100 if (BUNDLE) {101 return null;102 }103 return path.resolve(__dirname, "../resources");104}105/**...
index.spec.js
Source: index.spec.js
...34 });35 });36 describe("getIconFilename", function() {37 it("returns the correct filename for existing domains", function() {38 const filename = getIconFilename("qq.com");39 expect(filename).to.match(/qq_com\.png$/);40 });41 it("returns the correct filename for existing domains in greyscale", function() {42 const filename = getIconFilename("qq.com", { greyscale: true });43 expect(filename).to.match(/qq_com\.grey\.png$/);44 });45 it("returns the correct filename for existing domains when tested from a subdomain", function() {46 const filename = getIconFilename("sub.qq.com");47 expect(filename).to.match(/qq_com\.png$/);48 });49 it("returns the correct filename for non-existing domains", function() {50 const filename = getIconFilename("perrymitchell.net");51 expect(filename).to.match(/default\.png$/);52 });53 });54 describe("iconExists", function() {55 it("returns true for existing icons", function() {56 expect(iconExists("plex.tv")).to.be.true;57 });58 it("returns true for existing icons on subdomains", function() {59 expect(iconExists("login.auth.plex.tv")).to.be.true;60 });61 it("returns false for non-existing icons", function() {62 expect(iconExists("perrymitchell.net")).to.be.false;63 });64 });...
ToursItem.js
Source: ToursItem.js
1import React from 'react';2import Link from 'next/link';3import { object } from 'prop-types';4import { Routes } from '../../../settings';5import { LocalizationContext } from '../../../context';6const ToursItem = ({ name, id, region, visitTime, description, visitTimeType, transports, baseImagePath, cost, tourCategory }) => {7 const getIconFileName = (index) => {8 return [ '', 'icon-afoot.svg','icon-car.svg','icon-bus.svg','icon-afoot.svg','icon-afoot.svg',][index];9 }10 if (Array.isArray(transports) && transports.length > 3) {11 transports = transports.slice(0,3)12 }13 return (14 <LocalizationContext.Consumer>15 {16 ({localization}) => (17 <li className="tours-item">18 <div className="tours-item-img">19 <img src={baseImagePath} />20 </div>21 22 <div className="tours-item-wrapper">23 <div className="tours-item-title">24 <Link href={`${Routes.tours}/${id}/${name}`} as={`${Routes.tours}/${id}/${name}`}>25 <a><h3 className="tours-item-title-text">{name}</h3></a>26 </Link>27 </div>28 <div className="tours-item-info">29 <span className="tours-item-info-tag">{tourCategory}</span>30 <span className="tours-item-info-region">{region}</span>31 </div>32 <p className="tours-item-text">{description}</p>33 </div>34 35 <div className="tours-item-details">36 <table>37 <tbody>38 <tr>39 <td>{localization.tourCost}: </td>40 <td>41 <span className="tours-item-details-duration">{visitTime} {[localization.guidesHour, localization.guidesDay][visitTimeType -1]}</span>42 </td>43 </tr>44 <tr>45 <td>{cost}</td>46 <td>47 <span>48 { Array.isArray(transports) && transports.map((el, idx) => {49 return <img key={idx} src={`/static/images/icons/${getIconFileName(el.id)}`} alt="" style={{paddingRight:'10px'}}/>50 })51 }52 </span>53 </td>54 </tr>55 </tbody>56 57 </table>58 </div>59 </li>60 )61 }62 </LocalizationContext.Consumer>63 )64}...
MiddleBlock.jsx
Source: MiddleBlock.jsx
1import '../../css/middleBlockStyle.css';2import React from 'react';3import { connect } from 'react-redux';4import PropTypes from 'prop-types';5import cn from 'classnames';6import { getIconFileName, transformDegrees } from '../utils';7const getDescription = (text, mode) => {8 const textMapping = {9 loading: 'ÐагÑÑзка даннÑÑ
...',10 failure: 'Ðе ÑдалоÑÑ Ð·Ð°Ð³ÑÑзиÑÑ Ð´Ð°Ð½Ð½Ñе',11 geolocation_failure: 'Ðе ÑдалоÑÑ Ð¾Ð¿ÑеделиÑÑ Ð¼ÐµÑÑоположение',12 };13 return textMapping[mode] ? textMapping[mode] : text;14};15const mapStateToProps = (state) => {16 const { weatherData, degreesType, appMode } = state;17 return { weatherData, degreesType, appMode };18};19const MiddleBlock = (props) => {20 const { weatherData: { icon: iconId, temp, description }, degreesType, appMode } = props;21 const tempValue = `${degreesType === 'Celsius' ? temp : transformDegrees(temp)}°`;22 const iconFileName = `img/${getIconFileName(iconId)}.png`;23 const isWarning = appMode === 'loading'24 || appMode === 'failure'25 || appMode === 'geolocation_failure';26 const descriptionClass = cn('weather-desc', 'description-font', { 'warning-text': isWarning });27 return (28 <div className="info-area-item middle-block">29 <div className="main-block">30 <img className="weather-picture picture-size" src={iconFileName} alt="weather" data-testid="weather-icon" />31 <div className="temp-font temp" data-testid="temp">{tempValue}</div>32 </div>33 <div className={descriptionClass} data-testid="description">34 {getDescription(description, appMode)}35 </div>36 </div>37 );38};39MiddleBlock.propTypes = {40 weatherData: PropTypes.shape({41 icon: PropTypes.string,42 temp: PropTypes.number,43 description: PropTypes.string,44 }).isRequired,45 degreesType: PropTypes.string.isRequired,46 appMode: PropTypes.string.isRequired,47};...
Icon.js
Source: Icon.js
1import React from 'react';2import PropTypes from 'prop-types';3import Classnames from 'classnames';4export const iconContext = require.context("images/icons", true, /\.(png|jpg|svg)$/);5const Size = Object.freeze({6 SMALL: 'small',7 MEDIUM: 'medium',8 LARGE: 'large',9 XLARGE: 'x-large',10 MASSIVE: 'massive',11});12class Icon extends React.PureComponent {13 static get Size() {14 return Size;15 }16 getIconFileName() {17 if (this.props.color) {18 return `./${this.props.name}-${this.props.color}.svg`;19 }20 return `./${this.props.name}.svg`;21 }22 getIconClassName() {23 if (this.props.color) {24 return `--icon-${this.props.name}-${this.props.color}`;25 }26 return `--icon-${this.props.name}`;27 }28 render() {29 const classes = Classnames({30 'icon': true,31 [this.getIconClassName()]: true,32 [`--${this.props.size}`]: !!this.props.size,33 });34 const styles = this.props.style ? this.props.style : {};35 if (this.props.rotate) {36 styles.transform = `rotate(${this.props.rotate}deg)`;37 }38 styles.backgroundImage = `url(${iconContext(this.getIconFileName())})`;39 return (40 <i className={classes} style={styles} />41 );42 }43}44Icon.defaultProps = {45 size: Size.SMALL,46}47Icon.propTypes = {48 name: PropTypes.string.isRequired,49 rotate: PropTypes.number,50 size: PropTypes.oneOf(Object.values(Size)),51 color: PropTypes.string,52}...
entry-icon.js
Source: entry-icon.js
...27 return;28 }29 const url = getEntryURL(entry);30 const domain = url ? extractDomain(url) : null;31 setIcon(getIconFilename(domain));32 });33 return (34 <IconWrapper big={big}>35 <img src={icon} />36 </IconWrapper>37 );38};39EntryIcon.propTypes = {40 big: PropTypes.bool,41 entry: PropTypes.object42};...
utils.js
Source: utils.js
1export default function getIconFileName(type, isLightIcon) {2 return `icon-${type}${isLightIcon ? '-light' : ''}`;...
Using AI Code Generation
1const { getIconFilename } = require('cypress')2getIconFilename('check-circle')3getIconFilename('check-circle', 'solid')4getIconFilename('check-circle', 'regular')5getIconFilename('check-circle', 'light')6getIconFilename('check-circle', 'duotone')7const { getIconFilename } = require('cypress')8getIconFilename('check-circle')9getIconFilename('check-circle', 'solid')10getIconFilename('check-circle', 'regular')11getIconFilename('check-circle', 'light')12getIconFilename('check-circle', 'duotone')13const { getIconFilename } = require('cypress')14getIconFilename('check-circle')15getIconFilename('check-circle', 'solid')16getIconFilename('check-circle', 'regular')17getIconFilename('check-circle', 'light')18getIconFilename('check-circle', 'duotone')19const { getIconFilename } = require('cypress')20getIconFilename('check-circle')21getIconFilename('check-circle', 'solid')22getIconFilename('check-circle', 'regular')23getIconFilename('check-circle', 'light')24getIconFilename('check-circle', 'duotone')25const { getIconFilename } = require('cypress')
Using AI Code Generation
1describe('Test Cypress.Blob.getIconFilename', function() {2 it('Test getIconFilename', function() {3 cy.get('input[type="file"]').attachFile('test.png')4 cy.get('.network-put').click()5 cy.get('.network-put').should((xhr) => {6 expect(xhr).to.have.property('status', 200)7 cy.readFile('cypress/fixtures/test.png', 'base64').then((fileContent) => {8 Cypress.Blob.getIconFilename(fileContent).then((iconFilename) => {9 expect(iconFilename).to.equal('image.png')10 })11 })12 })13 })14})15describe('Test Cypress.Blob.getIconFilename', function() {16 it('Test getIconFilename', function() {17 cy.get('input[type="file"]').attachFile('test.png')18 cy.get('.network-put').click()19 cy.get('.network-put').should((xhr) => {20 expect(xhr).to.have.property('status', 200)21 cy.readFile('cypress/fixtures/test.png', 'base64').then((fileContent) => {22 Cypress.Blob.getIconFilename(fileContent).then((iconFilename) => {23 expect(iconFilename).to.equal('image.png')24 })25 })26 })27 })28})29Cypress.Commands.add('attachFile', { prevSubject: 'element' }, (subject, fileName, fileType = '') => {30 cy.log('Attaching file ' + fileName + ' to element')31 return cy.fixture(fileName, 'base64').then(Cypress.Blob.base64StringToBlob).then((blob) => {32 const testFile = new File([blob], fileName, { type: fileType })33 const dataTransfer = new DataTransfer()34 dataTransfer.items.add(testFile)35 })36})37{
Using AI Code Generation
1Cypress.Blob.getIconFilename('cypress.png').then((filename) => {2 cy.log(filename)3})4Cypress.Blob.getIconFilename = (iconName) => {5 const iconPath = path.resolve(__dirname, '..', 'fixtures', iconName)6 return Cypress.Blob.base64StringToBlob(Cypress.Blob.readBlob(iconPath, 'base64'))7}
Using AI Code Generation
1describe('Test', () => {2 it('should work', () => {3 cy.getIconFilename('iconName').then((fileName) => {4 cy.log(fileName);5 });6 });7});8Cypress.Commands.add('getIconFilename', (iconName) => {9 return cy.readFile(10 `node_modules/@salesforce-ux/design-system/assets/icons/${iconName}-sprite/svg/symbols.svg`11 );12});
Using AI Code Generation
1Cypress.Blob.getIconFilename('download.png').then((filename) => {2 cy.log(filename);3});4Cypress.Blob.getIconFilename = (iconName) => {5 return cy.readFile(`cypress/fixtures/icons/${iconName}`, 'base64');6};7{8 "staticFiles": {9 {"folder": "cypress/fixtures/icons", "url": "/icons", "options": {"index": false}}10 }11}12describe('Test', () => {13 it('test', () => {14 cy.get('[data-cy=download-csv]').then((element) => {15 const href = element.attr('href');16 const filename = href.substring(href.lastIndexOf('/') + 1);17 cy.request(`/icons/${filename}`).then((response) => {18 cy.wrap(response.body).should('equal', Cypress.Blob.getIconFilename(filename));19 });20 });21 });22});23describe('Test', () => {24 it('test', () => {25 cy.get('[data-cy=download-csv]').then((element) => {26 const href = element.attr('href');
Using AI Code Generation
1cy.task('log', 'hello world')2cy.task('log', { foo: 'bar' })3module.exports = (on, config) => {4 on('task', {5 log (message) {6 console.log(message)7 },8 })9}10cy.on('log:added', (attrs, log) => {11 if (log.get('name') === 'log') {12 console.log(log.get('message'))13 }14})15module.exports = (on, config) => {16 on('task', {17 log (message) {18 console.log(message)19 },20 })21}
Using AI Code Generation
1const iconFilename = getIconFilename('icon-1');2cy.fixture(iconFilename).then((icon) => {3 cy.get('.icon-1').matchImageSnapshot({4 customDiffConfig: { threshold: 0.0 },5 onBeforeScreenshot: (contentWindow) => {6 contentWindow.document.body.innerHTML = icon;7 },8 });9});10import { getIconFilename } from '../../test';11Cypress.Commands.add('getIconFilename', (iconName) => {12 return getIconFilename(iconName);13});14{15 "reporterOptions": {16 },17 "env": {18 }19}20const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');21module.exports = (on, config) => {
Cypress fixtures usage in TypeScript
Why is Cypress saying my element is detached after just running a get command?
Cypress - how to properly wait for result of an imported JS function
Waiting for a page to load - Cypress
Cypress Best Practice - Store and compare two values
Cypress: Re-use auth token across multiple API tests
Cypress: Conditional AssertionError
Cypress iterate through elements in an array
How to check that element has either of classes in Cypress?
Checking states of Slide toggle not working in Cypress Tests
The type definitions seem to think your alias
was of an element.Try adding a type on the parameter to the function passed to .then
:
.then((queries:any) => {
Check out the latest blogs from LambdaTest on this topic:
Selenium is still the most influential and well-developed framework for web automation testing. Being one of the best automation frameworks with constantly evolving features, it is poised to lead the industry in all aspects as compared to other trending frameworks like Cypress, Puppeteer, PlayWright, etc. Furthermore, using Selenium gives you the flexibility to use different programming languages like C#, Ruby, Perl, Java, Python, etc., and also accommodate different operating systems and web browsers for Selenium automation testing.
Sometimes referred to as automated UI testing or visual regression testing, VRT checks software from a purely visual standpoint (taking a screenshot and comparing it against another approved screenshot). Cypress is an emerging test automation framework that enables teams to ship high-quality products faster.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Automation Testing Tutorial.
Mockito is a unit testing framework for Java that simplifies the task of automation testing. It makes unit testing highly effective with clean tests, thanks to dependency injection and compile-time checks. In addition, Mockito helps improve the test independence of components being developed by helping you create objects that have no dependencies on a test-specific configuration. The most popular way of using Mockito is within the JUnit framework to help you write better tests.
Hola, testers! We are up with another round of exciting product updates to help scale your cross browser testing coverage. As spring cleaning looms, we’re presenting you product updates to put some spring in your testing workflow. Our development team has been working relentlessly to make our test execution platform more scalable and reliable than ever to accomplish all your testing requirements.
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!!