Best JavaScript code snippet using cypress
util.js
Source:util.js
...178 resolve(fn());179 }, ms);180 });181}182function mergeDeletedHeaders(before, after) {183 for (const k in before.headers) {184 // a header was deleted from `after` but was present in `before`, delete it in `before` too185 !after.headers[k] && delete before.headers[k];186 }187}188exports.mergeDeletedHeaders = mergeDeletedHeaders;189function mergeWithPreservedBuffers(before, after) {190 // lodash merge converts Buffer into Array (by design)191 // https://github.com/lodash/lodash/issues/2964192 // @see https://github.com/cypress-io/cypress/issues/15898193 lodash_1.default.mergeWith(before, after, (_a, b) => {194 if (b instanceof Buffer) {195 return b;196 }...
request.js
Source:request.js
1"use strict";2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }4 return new (P || (P = Promise))(function (resolve, reject) {5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }8 step((generator = generator.apply(thisArg, _arguments || [])).next());9 });10};11var __importDefault = (this && this.__importDefault) || function (mod) {12 return (mod && mod.__esModule) ? mod : { "default": mod };13};14Object.defineProperty(exports, "__esModule", { value: true });15exports.InterceptRequest = void 0;16const lodash_1 = __importDefault(require("lodash"));17const network_1 = require("../../../../network");18const debug_1 = __importDefault(require("debug"));19const url_1 = __importDefault(require("url"));20const types_1 = require("../../types");21const route_matching_1 = require("../route-matching");22const util_1 = require("../util");23const intercepted_request_1 = require("../intercepted-request");24const debug = (0, debug_1.default)('cypress:net-stubbing:server:intercept-request');25/**26 * Called when a new request is received in the proxy layer.27 */28const InterceptRequest = function () {29 return __awaiter(this, void 0, void 0, function* () {30 if ((0, route_matching_1.matchesRoutePreflight)(this.netStubbingState.routes, this.req)) {31 // send positive CORS preflight response32 return (0, util_1.sendStaticResponse)(this, {33 statusCode: 204,34 headers: {35 'access-control-max-age': '-1',36 'access-control-allow-credentials': 'true',37 'access-control-allow-origin': this.req.headers.origin || '*',38 'access-control-allow-methods': this.req.headers['access-control-request-method'] || '*',39 'access-control-allow-headers': this.req.headers['access-control-request-headers'] || '*',40 },41 });42 }43 const matchingRoutes = [];44 const populateMatchingRoutes = (prevRoute) => {45 const route = (0, route_matching_1.getRouteForRequest)(this.netStubbingState.routes, this.req, prevRoute);46 if (!route) {47 return;48 }49 matchingRoutes.push(route);50 populateMatchingRoutes(route);51 };52 populateMatchingRoutes();53 if (!matchingRoutes.length) {54 // not intercepted, carry on normally...55 return this.next();56 }57 const request = new intercepted_request_1.InterceptedRequest({58 continueRequest: this.next,59 onError: this.onError,60 onResponse: (incomingRes, resStream) => {61 (0, util_1.setDefaultHeaders)(this.req, incomingRes);62 this.onResponse(incomingRes, resStream);63 },64 req: this.req,65 res: this.res,66 socket: this.socket,67 state: this.netStubbingState,68 matchingRoutes,69 });70 debug('intercepting request %o', { requestId: request.id, req: lodash_1.default.pick(this.req, 'url') });71 // attach requestId to the original req object for later use72 this.req.requestId = request.id;73 this.netStubbingState.requests[request.id] = request;74 const req = lodash_1.default.extend(lodash_1.default.pick(request.req, types_1.SERIALIZABLE_REQ_PROPS), {75 url: request.req.proxiedUrl,76 });77 request.res.once('finish', () => __awaiter(this, void 0, void 0, function* () {78 request.handleSubscriptions({79 eventName: 'after:response',80 data: request.includeBodyInAfterResponse ? {81 finalResBody: request.res.body,82 } : {},83 mergeChanges: lodash_1.default.noop,84 });85 debug('request/response finished, cleaning up %o', { requestId: request.id });86 delete this.netStubbingState.requests[request.id];87 }));88 const ensureBody = () => {89 return new Promise((resolve) => {90 if (req.body) {91 return resolve();92 }93 request.req.pipe((0, network_1.concatStream)((reqBody) => {94 req.body = reqBody;95 resolve();96 }));97 });98 };99 yield ensureBody();100 if (!lodash_1.default.isString(req.body) && !lodash_1.default.isBuffer(req.body)) {101 throw new Error('req.body must be a string or a Buffer');102 }103 const bodyEncoding = (0, util_1.getBodyEncoding)(req);104 const bodyIsBinary = bodyEncoding === 'binary';105 if (bodyIsBinary) {106 debug('req.body contained non-utf8 characters, treating as binary content %o', { requestId: request.id, req: lodash_1.default.pick(this.req, 'url') });107 }108 // leave the requests that send a binary buffer unchanged109 // but we can work with the "normal" string requests110 if (!bodyIsBinary) {111 req.body = req.body.toString('utf8');112 }113 request.req.body = req.body;114 const mergeChanges = (before, after) => {115 if (before.headers['content-length'] === after.headers['content-length']) {116 // user did not purposely override content-length, let's set it117 after.headers['content-length'] = String(Buffer.from(after.body).byteLength);118 }119 // resolve and propagate any changes to the URL120 request.req.proxiedUrl = after.url = url_1.default.resolve(request.req.proxiedUrl, after.url);121 (0, util_1.mergeWithPreservedBuffers)(before, lodash_1.default.pick(after, types_1.SERIALIZABLE_REQ_PROPS));122 (0, util_1.mergeDeletedHeaders)(before, after);123 };124 const modifiedReq = yield request.handleSubscriptions({125 eventName: 'before:request',126 data: req,127 mergeChanges,128 });129 mergeChanges(req, modifiedReq);130 // @ts-ignore131 mergeChanges(request.req, req);132 if (request.responseSent) {133 // request has been fulfilled with a response already, do not send the request outgoing134 // @see https://github.com/cypress-io/cypress/issues/15841135 return this.end();136 }137 return request.continueRequest();138 });139};...
response.js
Source:response.js
1"use strict";2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }4 return new (P || (P = Promise))(function (resolve, reject) {5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }8 step((generator = generator.apply(thisArg, _arguments || [])).next());9 });10};11var __importDefault = (this && this.__importDefault) || function (mod) {12 return (mod && mod.__esModule) ? mod : { "default": mod };13};14Object.defineProperty(exports, "__esModule", { value: true });15exports.InterceptResponse = void 0;16const lodash_1 = __importDefault(require("lodash"));17const network_1 = require("../../../../network");18const debug_1 = __importDefault(require("debug"));19const istextorbinary_1 = require("istextorbinary");20const types_1 = require("../../types");21const util_1 = require("../util");22const debug = (0, debug_1.default)('cypress:net-stubbing:server:intercept-response');23const InterceptResponse = function () {24 return __awaiter(this, void 0, void 0, function* () {25 const request = this.netStubbingState.requests[this.req.requestId];26 debug('InterceptResponse %o', { req: lodash_1.default.pick(this.req, 'url'), request });27 if (!request) {28 // original request was not intercepted, nothing to do29 return this.next();30 }31 request.onResponse = (incomingRes, resStream) => {32 this.incomingRes = incomingRes;33 request.continueResponse(resStream);34 };35 request.continueResponse = (newResStream) => {36 if (newResStream) {37 this.incomingResStream = newResStream.on('error', this.onError);38 }39 this.next();40 };41 this.makeResStreamPlainText();42 const body = yield new Promise((resolve) => {43 if (network_1.httpUtils.responseMustHaveEmptyBody(this.req, this.incomingRes)) {44 resolve(Buffer.from(''));45 }46 else {47 this.incomingResStream.pipe((0, network_1.concatStream)(resolve));48 }49 })50 .then((buf) => {51 return (0, istextorbinary_1.getEncoding)(buf) !== 'binary' ? buf.toString('utf8') : buf;52 });53 const res = lodash_1.default.extend(lodash_1.default.pick(this.incomingRes, types_1.SERIALIZABLE_RES_PROPS), {54 url: this.req.proxiedUrl,55 body,56 });57 if (!lodash_1.default.isString(res.body) && !lodash_1.default.isBuffer(res.body)) {58 throw new Error('res.body must be a string or a Buffer');59 }60 const mergeChanges = (before, after) => {61 (0, util_1.mergeWithPreservedBuffers)(before, lodash_1.default.pick(after, types_1.SERIALIZABLE_RES_PROPS));62 (0, util_1.mergeDeletedHeaders)(before, after);63 };64 const modifiedRes = yield request.handleSubscriptions({65 eventName: ['before:response', 'response:callback', 'response'],66 data: res,67 mergeChanges,68 });69 mergeChanges(request.res, modifiedRes);70 const bodyStream = yield (0, util_1.getBodyStream)(modifiedRes.body, lodash_1.default.pick(modifiedRes, ['throttleKbps', 'delay']));71 return request.continueResponse(bodyStream);72 });73};...
Using AI Code Generation
1Cypress.Commands.add('mergeDeletedHeaders', (headers) => {2 let newHeaders = {};3 for (const [key, value] of Object.entries(headers)) {4 if (value !== null) {5 newHeaders[key] = value;6 }7 }8 return newHeaders;9});10Cypress.Commands.add('mergeDeletedHeaders', (headers) => {11 let newHeaders = {};12 for (const [key, value] of Object.entries(headers)) {13 if (value !== null) {14 newHeaders[key] = value;15 }16 }17 return newHeaders;18});19Cypress.Commands.add('mergeDeletedHeaders', (headers) => {20 let newHeaders = {};21 for (const [key, value] of Object.entries(headers)) {22 if (value !== null) {23 newHeaders[key] = value;24 }25 }26 return newHeaders;27});28Cypress.Commands.add('mergeDeletedHeaders', (headers) => {29 let newHeaders = {};30 for (const [key, value] of Object.entries(headers)) {31 if (value !== null) {32 newHeaders[key] = value;33 }34 }35 return newHeaders;36});37Cypress.Commands.add('mergeDeletedHeaders', (headers) => {38 let newHeaders = {};39 for (const [key, value] of Object.entries(headers)) {40 if (value !== null) {41 newHeaders[key] = value;42 }43 }44 return newHeaders;45});46Cypress.Commands.add('mergeDeletedHeaders', (headers) => {47 let newHeaders = {};48 for (const [key, value] of Object.entries(headers)) {49 if (value !== null) {50 newHeaders[key] = value;51 }52 }53 return newHeaders;54});55Cypress.Commands.add('mergeDeletedHeaders', (headers) => {56 let newHeaders = {};57 for (const [key, value] of Object
Using AI Code Generation
1const { mergeDeletedHeaders } = require('cypress/types/lodash')2describe('My First Test Suite', function() 3{4 it('My FirstTest case',function() {5 cy.get('#checkBoxOption1').check().should('be.checked').and('have.value','option1')6 cy.get('#checkBoxOption1').uncheck().should('not.be.checked')7 cy.get('input[type="checkbox"]').check(['option2','option3'])8 cy.get('select').select('option2').should('have.value','option2')9 cy.get('#autocomplete').type('ind')10 cy.get('.ui-menu-item div').each(($el, index, $list) => {11 if($el.text()==="India")12 {13 $el.click()14 }15 })16 cy.get('#autocomplete').should('have.value','India')17 cy.get('#displayed-text').should('be.visible')18 cy.get('#hide-textbox').click()19 cy.get('#displayed-text').should('not.be.visible')20 cy.get('#show-textbox').click()21 cy.get('#displayed-text').should('be.visible')22 cy.get('[value="radio2"]').check().should('be.checked')23 cy.get('tr td:nth-child(2)').each(($el, index, $list) => {24 const text=$el.text()25 if(text.includes("Python"))26 {27 cy.get('tr td:nth-child(2)').eq(index).next().then(function(price)28 {29 const priceText=price.text()30 expect(priceText).to.equal('25')31 })32 }33 })34 cy.get('.mouse-hover-content').invoke('show')35 cy.contains('Top').click()36 cy.url().should('include','top')37 cy.get('#alertbtn').click()38 cy.on('window:alert',(str)=>39 {40 expect(str).to.equal('Hello , share this practice page and share your knowledge')41 })42 cy.get('#opentab').invoke('removeAttr','target').click()43 cy.url().should('include','rahulshettyacademy')
Using AI Code Generation
1describe('Test mergeDeletedHeaders', () => {2 it('mergeDeletedHeaders', () => {3 cy.server()4 cy.route({5 response: {6 },7 headers: {8 }9 }).as('updateComment')10 cy.get('.network-put').click()11 cy.wait('@updateComment').its('response').should((res) => {12 expect(res.body.error).to.equal('Hey Comment not found')13 })14 })15})
Using AI Code Generation
1describe('Merge Deleted Headers', () => {2 it('should merge deleted headers from the request', () => {3 headers: {4 },5 }).as('getExample');6 cy.wait('@getExample').then((interception) => {7 const headers = Cypress.mergeDeletedHeaders(interception.request.headers, {8 });9 expect(headers).to.deep.equal({});10 });11 });12});
Using AI Code Generation
1Cypress.Commands.add('mergeDeletedHeaders', () => {2 cy.get('.header-row').then(($headers) => {3 cy.get('.header-row').then(($headers) => {4 let headers = [];5 for (let i = 0; i < $headers.length; i++) {6 let header = $headers[i].innerText;7 headers.push(header);8 }9 headers = headers.filter((header) => {10 return header !== 'Delete';11 });12 cy.get('.header-row').each(($header) => {13 let header = $header.text();14 if (header === 'Delete') {15 $header.remove();16 }17 });18 cy.get('.header-row').each(($header) => {19 let header = $header.text();20 if (header === 'Delete') {21 $header.remove();22 }23 });24 cy.get('.header-row').each(($header) => {25 let header = $header.text();26 if (header === 'Delete') {27 $header.remove();28 }29 });30 cy.get('.header-row').each(($header) => {31 let header = $header.text();32 if (header === 'Delete') {33 $header.remove();34 }35 });36 cy.get('.header-row').each(($header) => {37 let header = $header.text();38 if (header === 'Delete') {39 $header.remove();40 }41 });42 cy.get('.header-row').each(($header) => {43 let header = $header.text();44 if (header === 'Delete') {45 $header.remove();46 }47 });48 cy.get('.header-row').each(($header) => {49 let header = $header.text();50 if (header === 'Delete') {51 $header.remove();52 }53 });54 cy.get('.header-row').each(($header) => {55 let header = $header.text();56 if (header === 'Delete') {57 $header.remove();58 }59 });60 cy.get('.header-row').each(($header) => {61 let header = $header.text();62 if (header === 'Delete') {63 $header.remove();64 }65 });66 cy.get('.header-row').each(($header) => {67 let header = $header.text();68 if (header === 'Delete') {69 $header.remove();70 }71 });72 });73 });74});
Using AI Code Generation
1describe('Test to check if headers are merged', function () {2 it('test', function () {3 req.headers['x-foo'] = 'bar';4 req.headers['x-bar'] = 'foo';5 req.mergeDeletedHeaders();6 }).as('getGoogle');7 cy.wait('@getGoogle').then((interception) => {8 expect(interception.request.headers['x-foo']).to.eq('bar');9 expect(interception.request.headers['x-bar']).to.eq('foo');10 })11 })12})
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!!