Best JavaScript code snippet using cypress
cache_spec.js
Source:cache_spec.js
...14 this.oldCache = oldCache15 })16 })17 it('converts object to array of paths', function () {18 const obj = cache._applyRewriteRules(this.oldCache)19 expect(obj).to.deep.eq({20 USER: { name: 'brian', sessionToken: 'abc123' },21 PROJECTS: [22 '/Users/bmann/Dev/examples-angular-circle-ci',23 '/Users/bmann/Dev/cypress-core-gui',24 '/Users/bmann/Dev/cypress-app/spec/fixtures/projects/todos',25 ],26 })27 })28 it('compacts non PATH values', () => {29 const obj = cache._applyRewriteRules({30 USER: {},31 PROJECTS: {32 one: { PATH: 'foo/bar' },33 two: { FOO: 'baz' },34 },35 })36 expect(obj).to.deep.eq({37 USER: {},38 PROJECTS: ['foo/bar'],39 })40 })41 it('converts session_token to session_token', () => {42 const obj = cache._applyRewriteRules({43 USER: { id: 1, session_token: 'abc123' },44 PROJECTS: [],45 })46 expect(obj).to.deep.eq({47 USER: { id: 1, sessionToken: 'abc123' },48 PROJECTS: [],49 })50 })51 })52 context('projects', () => {53 describe('#insertProject', () => {54 it('inserts project by path', () => {55 return cache.insertProject('foo/bar')56 .then(() => {...
settings.js
Source:settings.js
...120 var changed;121 if (json == null) {122 json = {};123 }124 changed = _this._applyRewriteRules(json);125 if (_.isEqual(json, changed)) {126 return json;127 } else {128 return _this._write(file, changed);129 }130 };131 })(this))["catch"]((function(_this) {132 return function(err) {133 if (errors.isCypressErr(err)) {134 throw err;135 }136 return _this._logReadErr(file, err);137 };138 })(this));...
cache.js
Source:cache.js
1const _ = require('lodash')2const Promise = require('bluebird')3const { fs } = require('./util/fs')4const appData = require('./util/app_data')5const FileUtil = require('./util/file')6const logger = require('./logger')7const fileUtil = new FileUtil({8 path: appData.path('cache'),9})10const convertProjectsToArray = function (obj) {11 // if our project structure is not12 // an array then its legacy and we13 // need to convert it14 if (!_.isArray(obj.PROJECTS)) {15 obj.PROJECTS = _.chain(obj.PROJECTS).values().map('PATH').compact().value()16 return obj17 }18}19const renameSessionToken = function (obj) {20 let st21 if (obj.USER && (st = obj.USER.session_token)) {22 delete obj.USER.session_token23 obj.USER.sessionToken = st24 return obj25 }26}27module.exports = {28 path: fileUtil.path,29 defaults () {30 return {31 USER: {},32 PROJECTS: [],33 }34 },35 _applyRewriteRules (obj = {}) {36 return _.reduce([convertProjectsToArray, renameSessionToken], (memo, fn) => {37 let ret38 ret = fn(memo)39 if (ret) {40 return ret41 }42 return memo43 }44 , _.cloneDeep(obj))45 },46 read () {47 return fileUtil.get().then((contents) => {48 return _.defaults(contents, this.defaults())49 })50 },51 write (obj = {}) {52 logger.info('writing to .cy cache', { cache: obj })53 return fileUtil.set(obj).return(obj)54 },55 _getProjects (tx) {56 return tx.get('PROJECTS', [])57 },58 _removeProjects (tx, projects, paths) {59 // normalize paths in array60 projects = _.without(projects, ...[].concat(paths))61 return tx.set({ PROJECTS: projects })62 },63 getProjectRoots () {64 return fileUtil.transaction((tx) => {65 return this._getProjects(tx).then((projects) => {66 const pathsToRemove = Promise.reduce(projects, (memo, path) => {67 return fs.statAsync(path)68 .catch(() => {69 return memo.push(path)70 }).return(memo)71 }72 , [])73 return pathsToRemove.then((removedPaths) => {74 return this._removeProjects(tx, projects, removedPaths)75 }).then(() => {76 return this._getProjects(tx)77 })78 })79 })80 },81 removeProject (path) {82 return fileUtil.transaction((tx) => {83 return this._getProjects(tx).then((projects) => {84 return this._removeProjects(tx, projects, path)85 })86 })87 },88 insertProject (path) {89 return fileUtil.transaction((tx) => {90 return this._getProjects(tx).then((projects) => {91 // projects are sorted by most recently used, so add a project to92 // the start or move it to the start if it already exists93 const existingIndex = _.findIndex(projects, (project) => {94 return project === path95 })96 if (existingIndex > -1) {97 projects.splice(existingIndex, 1)98 }99 projects.unshift(path)100 return tx.set('PROJECTS', projects)101 })102 })103 },104 getUser () {105 logger.info('getting user')106 return fileUtil.get('USER', {})107 },108 setUser (user) {109 logger.info('setting user', { user })110 return fileUtil.set({ USER: user })111 },112 removeUser () {113 return fileUtil.set({ USER: {} })114 },115 remove () {116 return fileUtil.remove()117 },118 // for testing purposes119 __get: fileUtil.get.bind(fileUtil),120 __removeSync () {121 fileUtil._cache = {}122 return fs.removeSync(this.path)123 },...
Using AI Code Generation
1Cypress.Commands.add('applyRewriteRules', (url) => {2 return cy.window().then((win) => {3 return win.Cypress._applyRewriteRules(url);4 });5});6Cypress.Commands.add('applyRewriteRules', (url) => {7 return cy.window().then((win) => {8 return win.Cypress._applyRewriteRules(url);9 });10});11it('test', () => {12 cy.visit(url);13 });14});15});
Using AI Code Generation
1const fs = require('fs');2const path = require('path');3const _ = require('lodash');4const Promise = require('bluebird');5const debug = require('debug')('cypress:server:rewrite_rules');6const errors = require('../errors');7const util = require('./util');8const { getProxyUrl } = require('./util/url');9const readFile = Promise.promisify(fs.readFile);10const getRewriteRules = function (filePath) {11 return readFile(filePath, 'utf8')12 .then(JSON.parse)13 .catch((err) => {14 debug('Error reading rewrite rules file: %o', err);15 throw errors.get('ERROR_READING_REWRITE_RULES_FILE', filePath);16 });17};18const getRewriteRulesPath = function (config) {19 const rulesPath = config.env.rewriteRulesPath;20 if (!rulesPath) {21 return null;22 }23 const absolutePath = path.resolve(config.projectRoot, rulesPath);24 return absolutePath;25};26const applyRewriteRules = function (config, rules, url) {27 const proxyUrl = getProxyUrl(config);28 if (!proxyUrl) {29 return url;30 }31 const proxyHost = util.getHostFromUrl(proxyUrl);32 const host = util.getHostFromUrl(url);33 if (host !== proxyHost) {34 return url;35 }36 const path = util.getPathFromUrl(url);37 return _.reduce(rules, (acc, rule) => {38 if (acc === url) {39 return acc;40 }41 const { from, to } = rule;42 return acc.replace(from, to);43 }, url);44};45const applyRewriteRulesToUrls = function (config, rules, urls) {46 return _.map(urls, (url) => {47 return applyRewriteRules(config, rules, url);48 });49};50const applyRewriteRulesToRequests = function (config, rules, requests) {51 return _.map(requests, (request) => {52 const url = applyRewriteRules(config, rules, request.url);53 return _.extend({}, request, { url });54 });55};56module.exports = {57};
Using AI Code Generation
1const { _applyRewriteRules } = Cypress2Cypress.Commands.overwrite('visit', (originalFn, url, options) => {3 const { host, protocol, port } = Cypress.config()4 const rewrittenUrl = _applyRewriteRules({ url, host, port, protocol })5 return originalFn(rewrittenUrl, options)6})7Cypress.Commands.add('login', (email, password) => {8})9Cypress.Commands.add('logout', () => {10})11describe('Login', () => {12 it('should login successfully', () => {13 cy.login('
Using AI Code Generation
1Cypress.on('window:before:load', win => {2 win.XMLHttpRequest.prototype.open = function (method, url) {3 const newUrl = Cypress._.applyRewriteRules(url, Cypress.config('baseUrl'), Cypress.config('url'))4 originalXhrOpen.apply(this, [method, newUrl])5 }6})7 {8 }9Cypress._ = {10 applyRewriteRules (url, baseUrl, configUrl) {11 const rules = urlRewriteRules.concat(Cypress.env('rewriteRules') || [])12 for (const rule of rules) {13 if (url === rule.from || url === baseUrl + rule.from) {14 }15 }16 }17}18{19 "env": {20 {21 }22 }23}24describe('test', () => {25 it('test', () => {26 cy.request('GET', '/todos/1').then((response) => {27 expect(response.status).to.eq(200)28 expect(response.body).to.have.property('userId', 1)29 expect(response.body).to.have.property('id', 1)30 expect(response.body).to.have.property('title', 'delectus aut autem')31 expect(response.body).to.have.property('completed', false)
Using AI Code Generation
1const fs = require("fs");2const rules = fs.readFileSync("rules.json");3const cy = {4 state: () => {5 return {6 currentTest: {7 }8 };9 },10 log: () => {11 return {12 end: () => {}13 };14 },15 _applyRewriteRules: () => {}16};17cy._applyRewriteRules(url, rules);
Using AI Code Generation
1Cypress.on('before:browser:launch', (browser = {}, launchOptions) => {2 if (browser.family === 'chromium' && browser.name !== 'electron') {3 launchOptions.args.push('--disable-blink-features=AutomationControlled')4 launchOptions.args.push('--disable-site-isolation-trials')5 launchOptions.args.push('--disable-web-security')6 launchOptions.args.push('--disable-features=IsolateOrigins,site-per-process')7 launchOptions.args.push('--disable-site-isolation-trials')8 launchOptions.args.push('--no-first-run')9 launchOptions.args.push('--no-sandbox')10 launchOptions.args.push('--no-zygote')11 launchOptions.args.push('--use-fake-ui-for-media-stream')12 launchOptions.args.push('--use-fake-device-for-media-stream')13 launchOptions.args.push('--use-file-for-fake-audio-capture')14 launchOptions.args.push('--disable-web-security')15 launchOptions.args.push('--disable-features=IsolateOrigins,site-per-process')16 launchOptions.args.push('--disable-site-isolation-trials')17 launchOptions.args.push('--no-first-run')18 launchOptions.args.push('--no-sandbox')19 launchOptions.args.push('--no-zygote')20 launchOptions.args.push('--use-fake-ui-for-media-stream')21 launchOptions.args.push('--use-fake-device-for-media-stream')22 launchOptions.args.push('--use-file-for-fake-audio-capture')23 launchOptions.args.push('--disable-web-security')24 launchOptions.args.push('--disable-features=IsolateOrigins,site-per-process')25 launchOptions.args.push('--disable-site-isolation-trials')26 launchOptions.args.push('--no-first-run')27 launchOptions.args.push('--no-sandbox')28 launchOptions.args.push('--no-zygote')29 launchOptions.args.push('--use-fake-ui-for-media-stream')30 launchOptions.args.push('--use-fake-device-for-media-stream')31 launchOptions.args.push('--use-file-for-fake-audio-capture')32 launchOptions.args.push('--disable-web-security')33 launchOptions.args.push('--disable-features=IsolateOrigins,site-per-process')34 launchOptions.args.push('--disable
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!!