Best JavaScript code snippet using cypress
agent.js
Source:agent.js
...60 };61 if (!opts.shouldRetry) {62 connectOpts.getDelayMsForRetry = function () { return undefined; };63 }64 connect_1.createRetryingSocket(connectOpts, function (err, sock, triggerRetry) {65 if (err) {66 return cb(err);67 }68 cb(undefined, sock, triggerRetry);69 });70};71exports.isRequestHttps = function (options) {72 // WSS connections will not have an href, but you can tell protocol from the defaultAgent73 return lodash_1.default.get(options, '_defaultAgent.protocol') === 'https:' || (options.href || '').slice(0, 6) === 'https';74};75exports.isResponseStatusCode200 = function (head) {76 // read status code from proxy's response77 var matches = head.match(statusCodeRe);78 return lodash_1.default.get(matches, 1) === '200';...
proxy_spec.js
Source:proxy_spec.js
1process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'2const { request, expect } = require('../spec_helper')3const DebugProxy = require('@cypress/debugging-proxy')4const https = require('https')5const net = require('net')6const network = require('@packages/network')7const Promise = require('bluebird')8const proxy = require('../helpers/proxy')9const httpServer = require('../helpers/http_server')10const httpsServer = require('../helpers/https_server')11describe('Proxy', () => {12 beforeEach(function () {13 return Promise.join(14 httpServer.start(),15 httpsServer.start(8443),16 httpsServer.start(8444),17 proxy.start(3333)18 .then((proxy1) => {19 this.proxy = proxy120 }),21 )22 })23 afterEach(() => {24 return Promise.join(25 httpServer.stop(),26 httpsServer.stop(),27 proxy.stop(),28 )29 })30 it('can request the googles', function () {31 // give some padding to external32 // network request33 this.timeout(10000)34 return Promise.all([35 request({36 strictSSL: false,37 proxy: 'http://localhost:3333',38 url: 'https://www.google.com',39 }),40 request({41 strictSSL: false,42 proxy: 'http://localhost:3333',43 url: 'https://mail.google.com',44 }),45 request({46 strictSSL: false,47 proxy: 'http://localhost:3333',48 url: 'https://google.com',49 }),50 ])51 })52 it('can call the httpsDirectly without a proxy', () => {53 return request({54 strictSSL: false,55 url: 'https://localhost:8443',56 })57 })58 it('can boot the httpsServer', () => {59 return request({60 strictSSL: false,61 url: 'https://localhost:8443/',62 proxy: 'http://localhost:3333',63 })64 .then((html) => {65 expect(html).to.include('https server')66 })67 })68 it('yields the onRequest callback', () => {69 return request({70 strictSSL: false,71 url: 'https://localhost:8443/replace',72 proxy: 'http://localhost:3333',73 })74 .then((html) => {75 expect(html).to.include('replaced content')76 })77 })78 it('closes outgoing connections when client disconnects', function () {79 this.sandbox.spy(net, 'connect')80 return request({81 strictSSL: false,82 url: 'https://localhost:8444/replace',83 proxy: 'http://localhost:3333',84 resolveWithFullResponse: true,85 })86 .then((res) => {87 // ensure client has disconnected88 expect(res.socket.destroyed).to.be.true89 // ensure the outgoing socket created for this connection was destroyed90 expect(net.connect).calledOnce91 const socket = net.connect.getCalls()[0].returnValue92 return new Promise((resolve) => {93 socket.on('close', () => {94 expect(socket.destroyed).to.be.true95 resolve()96 })97 })98 })99 })100 it('can boot the httpServer', () => {101 return request({102 strictSSL: false,103 url: 'http://localhost:8080/',104 proxy: 'http://localhost:3333',105 })106 .then((html) => {107 expect(html).to.include('http server')108 })109 })110 context('generating certificates', () => {111 it('reuses existing certificates', function () {112 return request({113 strictSSL: false,114 url: 'https://localhost:8443/',115 proxy: 'http://localhost:3333',116 })117 .then(() => {118 proxy.reset()119 // force this to reject if its called120 this.sandbox.stub(this.proxy, '_generateMissingCertificates').rejects(new Error('should not call'))121 return request({122 strictSSL: false,123 url: 'https://localhost:8443/',124 proxy: 'http://localhost:3333',125 })126 })127 })128 // https://github.com/cypress-io/cypress/issues/771129 it('generates certs and can proxy requests for HTTPS requests to IPs', function () {130 this.sandbox.spy(this.proxy, '_generateMissingCertificates')131 this.sandbox.spy(this.proxy, '_getServerPortForIp')132 return Promise.all([133 httpsServer.start(8445),134 this.proxy._ca.removeAll(),135 ])136 .then(() => {137 return request({138 strictSSL: false,139 url: 'https://127.0.0.1:8445/',140 proxy: 'http://localhost:3333',141 })142 }).then(() => {143 // this should not stand up its own https server144 return request({145 strictSSL: false,146 url: 'https://localhost:8443/',147 proxy: 'http://localhost:3333',148 })149 }).then(() => {150 expect(this.proxy._ipServers['127.0.0.1']).to.be.an.instanceOf(https.Server)151 expect(this.proxy._getServerPortForIp).to.be.calledWith('127.0.0.1').and.be.calledOnce152 expect(this.proxy._generateMissingCertificates).to.be.calledTwice153 })154 })155 })156 context('closing', () => {157 it('resets sslServers and can reopen', function () {158 return request({159 strictSSL: false,160 url: 'https://localhost:8443/',161 proxy: 'http://localhost:3333',162 })163 .then(() => {164 return proxy.stop()165 }).then(() => {166 return proxy.start(3333)167 }).then(() => {168 // force this to reject if its called169 this.sandbox.stub(this.proxy, '_generateMissingCertificates').rejects(new Error('should not call'))170 return request({171 strictSSL: false,172 url: 'https://localhost:8443/',173 proxy: 'http://localhost:3333',174 })175 })176 })177 })178 // TODO179 context('with an upstream proxy', () => {180 beforeEach(function () {181 // PROXY vars should override npm_config vars, so set them to cause failures if they are used182 // @see https://github.com/cypress-io/cypress/pull/8295183 process.env.npm_config_proxy = process.env.npm_config_https_proxy = 'http://erroneously-used-npm-proxy.invalid'184 process.env.npm_config_noproxy = 'just,some,nonsense'185 process.env.NO_PROXY = ''186 process.env.HTTP_PROXY = process.env.HTTPS_PROXY = 'http://localhost:9001'187 this.upstream = new DebugProxy({188 keepRequests: true,189 })190 return this.upstream.start(9001)191 })192 it('passes a request to an https server through the upstream', function () {193 this.upstream._onConnect = function (domain, port) {194 expect(domain).to.eq('localhost')195 expect(port).to.eq('8444')196 return true197 }198 return request({199 strictSSL: false,200 url: 'https://localhost:8444/',201 proxy: 'http://localhost:3333',202 }).then((res) => {203 expect(res).to.contain('https server')204 })205 })206 it('uses HTTP basic auth when provided', function () {207 this.upstream.setAuth({208 username: 'foo',209 password: 'bar',210 })211 this.upstream._onConnect = function (domain, port) {212 expect(domain).to.eq('localhost')213 expect(port).to.eq('8444')214 return true215 }216 process.env.HTTP_PROXY = (process.env.HTTPS_PROXY = 'http://foo:bar@localhost:9001')217 return request({218 strictSSL: false,219 url: 'https://localhost:8444/',220 proxy: 'http://localhost:3333',221 }).then((res) => {222 expect(res).to.contain('https server')223 })224 })225 it('closes outgoing connections when client disconnects', function () {226 this.sandbox.spy(net, 'connect')227 return request({228 strictSSL: false,229 url: 'https://localhost:8444/replace',230 proxy: 'http://localhost:3333',231 resolveWithFullResponse: true,232 forever: false,233 })234 .then((res) => {235 // ensure client has disconnected236 expect(res.socket.destroyed).to.be.true237 // ensure the outgoing socket created for this connection was destroyed238 expect(net.connect).calledOnce239 const socket = net.connect.getCalls()[0].returnValue240 return new Promise((resolve) => {241 return socket.on('close', () => {242 expect(socket.destroyed).to.be.true243 resolve()244 })245 })246 })247 })248 // https://github.com/cypress-io/cypress/issues/4257249 it('passes through to SNI when it is intercepted and not through proxy', function () {250 const createSocket = this.sandbox.stub(network.connect, 'createRetryingSocket').callsArgWith(1, new Error('stub'))251 const createProxyConn = this.sandbox.spy(network.agent.httpsAgent, 'createUpstreamProxyConnection')252 return request({253 strictSSL: false,254 url: 'https://localhost:8443',255 proxy: 'http://localhost:3333',256 resolveWithFullResponse: true,257 forever: false,258 })259 .then(() => {260 throw new Error('should not succeed')261 }).catch({ message: 'Error: Client network socket disconnected before secure TLS connection was established' }, () => {262 expect(createProxyConn).to.not.be.called263 expect(createSocket).to.be.calledWith({264 port: this.proxy._sniPort,265 host: 'localhost',266 })267 })268 })269 return afterEach(function () {270 this.upstream.stop()271 delete process.env.HTTP_PROXY272 delete process.env.HTTPS_PROXY273 delete process.env.NO_PROXY274 })275 })...
server.js
Source:server.js
...103 }104 if (!port) {105 port = '443'106 }107 return connect.createRetryingSocket({ port, host: hostname }, onSocket)108 }109 _onServerConnectData (req, browserSocket, head) {110 let sem; let sslServer111 const firstBytes = head[0]112 const makeConnection = (port) => {113 debug('Making intercepted connection to %s', port)114 return this._makeConnection(browserSocket, head, port, 'localhost')115 }116 if (!SSL_RECORD_TYPES.includes(firstBytes)) {117 // if this isn't an SSL request then go118 // ahead and make the connection now119 return makeConnection(this._port)120 }121 // else spin up the SNI server...
connect.js
Source:connect.js
...56 return tls_1.default.connect(netOpts, onConnect);57 }58 return net_1.default.connect(netOpts, onConnect);59}60function createRetryingSocket(opts, cb) {61 if (typeof opts.getDelayMsForRetry === 'undefined') {62 opts.getDelayMsForRetry = getDelayForRetry;63 }64 function tryConnect(iteration = 0) {65 const retry = (err) => {66 const delay = opts.getDelayMsForRetry(iteration, err);67 if (typeof delay === 'undefined') {68 debug('retries exhausted, bubbling up error %o', { iteration, err });69 return cb(err);70 }71 debug('received error on connect, retrying %o', { iteration, delay, err });72 setTimeout(() => {73 tryConnect(iteration + 1);74 }, delay);...
protocol.js
Source:protocol.js
...15 }16}17function _connectAsync (opts) {18 return Promise.fromCallback((cb) => {19 connect.createRetryingSocket({20 getDelayMsForRetry: _getDelayMsForRetry,21 ...opts,22 }, cb)23 })24 .then((sock) => {25 // can be closed, just needed to test the connection26 sock.end()27 })28 .catch((err) => {29 errors.throw('CDP_COULD_NOT_CONNECT', opts.port, err)30 })31}32/**33 * Waits for the port to respond with connection to Chrome Remote Interface...
Using AI Code Generation
1socket.on('connect', () => {2 console.log('connected')3})4socket.on('event', (data) => {5 console.log('event', data)6})7socket.on('disconnect', () => {8 console.log('disconnected')9})10socket.on('error', (error) => {11 console.log('error', error)12})13Cypress.Commands.add('createRetryingSocket', (url, options) => {14 const socket = new WebSocket(url, options)15 const retryingSocket = {16 on: (event, callback) => {17 socket.addEventListener(event, (event) => {18 if (event.type === 'error') {19 return retryingSocket.on(event.type, callback)20 }21 callback(event)22 })23 },24 send: (data) => {25 if (socket.readyState === WebSocket.OPEN) {26 return socket.send(data)27 }28 return retryingSocket.send(data)29 },30 }31})32 socket.on('connect', () => {33 console.log('connected')34 })35 socket.on('event', (data) => {36 console.log('event', data)37 })38 socket.on('disconnect', () => {39 console.log('disconnected')40 })41 socket.on('error', (error) => {42 console.log('error', error)43 })44})
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 socket.on('connect', () => {4 });5 });6 });7});
Using AI Code Generation
1const createRetryingSocket = (url) => {2 const socket = new WebSocket(url);3 const originalOpen = socket.open;4 socket.open = function () {5 return new Promise((resolve, reject) => {6 const retry = () => {7 originalOpen.apply(socket, arguments);8 };9 socket.addEventListener("open", resolve);10 socket.addEventListener("error", retry);11 retry();12 });13 };14 return socket;15};16const createRetryingSocket = (url) => {17 const socket = new WebSocket(url);18 const originalOpen = socket.open;19 socket.open = function () {20 return new Promise((resolve, reject) => {21 const retry = () => {22 originalOpen.apply(socket, arguments);23 };24 socket.addEventListener("open", resolve);25 socket.addEventListener("error", retry);26 retry();27 });28 };29 return socket;30};31const createRetryingSocket = (url) => {32 const socket = new WebSocket(url);33 const originalOpen = socket.open;34 socket.open = function () {35 return new Promise((resolve, reject) => {36 const retry = () => {37 originalOpen.apply(socket, arguments);38 };39 socket.addEventListener("open", resolve);40 socket.addEventListener("error", retry);41 retry();42 });43 };44 return socket;45};46const createRetryingSocket = (url) => {47 const socket = new WebSocket(url);48 const originalOpen = socket.open;49 socket.open = function () {50 return new Promise((resolve, reject) => {51 const retry = () => {52 originalOpen.apply(socket, arguments);53 };54 socket.addEventListener("open", resolve);55 socket.addEventListener("error", retry);56 retry();57 });58 };59 return socket;60};61const createRetryingSocket = (url) => {62 const socket = new WebSocket(url);63 const originalOpen = socket.open;64 socket.open = function () {65 return new Promise((resolve, reject) => {66 const retry = () => {67 originalOpen.apply(socket, arguments);68 };69 socket.addEventListener("open", resolve);70 socket.addEventListener("error", retry);
Using AI Code Generation
1});2socket.on('connect', () => {3 socket.emit('event', 'data');4 socket.on('event', (data) => {5 console.log('data', data);6 });7});8A Javascript client library for the browser (which can be also run from Node.js): Source | API9In your Cypress support file (usually cypress/support/index.js ), import the plugin:10import 'cypress-socket-io-plugin';11}).on('connect', () => {12 cy.socket().emit('event', 'data');13 cy.socket().on('event', (data) => {14 console.log('data', data);15 });16});17A Javascript client library for the browser (which can be also run from Node.js): Source | API
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.get('socket').should('have.attr', 'id', 'socket')4 })5})6Cypress.Commands.add('createRetryingSocket', (url, alias) => {7 cy.window().then(win => {8 const socket = new win.WebSocket(url)9 const retry = () => {10 cy.wait(1000)11 cy.createRetryingSocket(url, alias)12 }13 socket.onopen = () => {14 cy.log('socket opened')15 cy.wrap(socket).as(alias)16 }17 socket.onclose = () => {18 cy.log('socket closed')19 retry()20 }21 socket.onerror = () => {22 cy.log('socket error')23 retry()24 }25 })26})
Using AI Code Generation
1const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket2const socket = createRetryingSocket('localhost', 3000)3const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket4const socket = createRetryingSocket('localhost', 3000)5const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket6const socket = createRetryingSocket('localhost', 3000)7const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket8const socket = createRetryingSocket('localhost', 3000)9const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket10const socket = createRetryingSocket('localhost', 3000)11const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket12const socket = createRetryingSocket('localhost', 3000)13const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket14const socket = createRetryingSocket('localhost', 3000)15const createRetryingSocket = require('cypress/lib/socket').createRetryingSocket16const socket = createRetryingSocket('localhost', 3000)
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!!