How to use this.server._onResolveUrl method in Cypress

Best JavaScript code snippet using cypress

server_spec.js

Source:server_spec.js Github

copy

Full Screen

...101          },102        })103      })104      it('can serve static assets', function () {105        return this.server._onResolveUrl('/index.html', {}, this.automationRequest)106        .then((obj = {}) => {107          return expectToEqDetails(obj, {108            isOkStatusCode: true,109            isHtml: true,110            contentType: 'text/html',111            url: 'http://localhost:2000/index.html',112            originalUrl: '/index.html',113            filePath: Fixtures.projectPath('no-server/dev/index.html'),114            status: 200,115            statusText: 'OK',116            redirects: [],117            cookies: [],118          })119        }).then(() => {120          return this.rp('http://localhost:2000/index.html')121          .then((res) => {122            expect(res.statusCode).to.eq(200)123            expect(res.headers['etag']).to.exist124            expect(res.headers['set-cookie']).not.to.match(/initial=;/)125            expect(res.headers['cache-control']).to.eq('no-cache, no-store, must-revalidate')126            expect(res.body).to.include('index.html content')127            expect(res.body).to.include('document.domain = \'localhost\'')128            expect(res.body).to.include('.action("app:window:before:load",window)')129            expect(res.body).to.include('</script>\n  </head>')130          })131        })132      })133      it('sends back the content type', function () {134        return this.server._onResolveUrl('/assets/foo.json', {}, this.automationRequest)135        .then((obj = {}) => {136          return expectToEqDetails(obj, {137            isOkStatusCode: true,138            isHtml: false,139            contentType: 'application/json',140            url: 'http://localhost:2000/assets/foo.json',141            originalUrl: '/assets/foo.json',142            filePath: Fixtures.projectPath('no-server/dev/assets/foo.json'),143            status: 200,144            statusText: 'OK',145            redirects: [],146            cookies: [],147          })148        })149      })150      it('buffers the response', function () {151        sinon.spy(this.server.request, 'sendStream')152        return this.server._onResolveUrl('/index.html', {}, this.automationRequest)153        .then((obj = {}) => {154          expectToEqDetails(obj, {155            isOkStatusCode: true,156            isHtml: true,157            contentType: 'text/html',158            url: 'http://localhost:2000/index.html',159            originalUrl: '/index.html',160            filePath: Fixtures.projectPath('no-server/dev/index.html'),161            status: 200,162            statusText: 'OK',163            redirects: [],164            cookies: [],165          })166          expect(this.buffers.buffer).to.include({ url: 'http://localhost:2000/index.html' })167        }).then(() => {168          return this.server._onResolveUrl('/index.html', {}, this.automationRequest)169          .then((obj = {}) => {170            expectToEqDetails(obj, {171              isOkStatusCode: true,172              isHtml: true,173              contentType: 'text/html',174              url: 'http://localhost:2000/index.html',175              originalUrl: '/index.html',176              filePath: Fixtures.projectPath('no-server/dev/index.html'),177              status: 200,178              statusText: 'OK',179              redirects: [],180              cookies: [],181            })182            expect(this.server.request.sendStream).to.be.calledTwice183          })184        }).then(() => {185          return this.rp('http://localhost:2000/index.html')186          .then((res) => {187            expect(res.statusCode).to.eq(200)188            expect(res.body).to.include('document.domain')189            expect(res.body).to.include('localhost')190            expect(res.body).to.include('Cypress')191            expect(this.buffers.buffer).to.be.undefined192          })193        })194      })195      it('can follow static file redirects', function () {196        return this.server._onResolveUrl('/sub', {}, this.automationRequest)197        .then((obj = {}) => {198          return expectToEqDetails(obj, {199            isOkStatusCode: true,200            isHtml: true,201            contentType: 'text/html',202            url: 'http://localhost:2000/sub/',203            originalUrl: '/sub',204            filePath: Fixtures.projectPath('no-server/dev/sub/'),205            status: 200,206            statusText: 'OK',207            redirects: ['301: http://localhost:2000/sub/'],208            cookies: [],209          })210        }).then(() => {211          return this.rp('http://localhost:2000/sub/')212          .then((res) => {213            expect(res.statusCode).to.eq(200)214            expect(this.server._getRemoteState()).to.deep.eq({215              auth: undefined,216              origin: 'http://localhost:2000',217              strategy: 'file',218              visiting: false,219              domainName: 'localhost',220              fileServer: this.fileServer,221              props: null,222            })223          })224        })225      })226      it('gracefully handles 404', function () {227        return this.server._onResolveUrl('/does-not-exist', {}, this.automationRequest)228        .then((obj = {}) => {229          return expectToEqDetails(obj, {230            isOkStatusCode: false,231            isHtml: true,232            contentType: 'text/html',233            url: 'http://localhost:2000/does-not-exist',234            originalUrl: '/does-not-exist',235            filePath: Fixtures.projectPath('no-server/dev/does-not-exist'),236            status: 404,237            statusText: 'Not Found',238            redirects: [],239            cookies: [],240          })241        }).then(() => {242          return this.rp('http://localhost:2000/does-not-exist')243          .then((res) => {244            expect(res.statusCode).to.eq(404)245            expect(res.body).to.include('Cypress errored trying to serve this file from your system:')246            expect(res.body).to.include('does-not-exist')247            expect(res.body).to.include('The file was not found')248          })249        })250      })251      it('handles urls with hashes', function () {252        return this.server._onResolveUrl('/index.html#/foo/bar', {}, this.automationRequest)253        .then((obj = {}) => {254          expectToEqDetails(obj, {255            isOkStatusCode: true,256            isHtml: true,257            contentType: 'text/html',258            url: 'http://localhost:2000/index.html',259            originalUrl: '/index.html',260            filePath: Fixtures.projectPath('no-server/dev/index.html'),261            status: 200,262            statusText: 'OK',263            redirects: [],264            cookies: [],265          })266          expect(this.buffers.buffer).to.include({ url: 'http://localhost:2000/index.html' })267        }).then(() => {268          return this.rp('http://localhost:2000/index.html')269          .then((res) => {270            expect(res.statusCode).to.eq(200)271            expect(this.buffers.buffer).to.be.undefined272          })273        })274      })275    })276    describe('http', () => {277      beforeEach(function () {278        return this.setup({279          projectRoot: '/foo/bar/',280          config: {281            port: 2000,282          },283        })284      })285      context('only having one request in flight at a time', () => {286        beforeEach(function (done) {287          this.httpServer = http.createServer((req, res) => {288            const [path, ms] = req.url.split('/').slice(1)289            switch (path) {290              case 'pause-before-body':291                res.writeHead(200, { 'content-type': 'text/html' })292                return setTimeout(() => {293                  res.write('ok')294                  return res.end()295                }296                , Number(ms))297              case 'pause-before-headers':298                return setTimeout(() => {299                  res.writeHead(200, { 'content-type': 'text/html' })300                  res.write('ok')301                  return res.end()302                }303                , Number(ms))304              default:305            }306          })307          this.httpServer.listen(() => {308            this.httpPort = this.httpServer.address().port309            return done()310          })311          this.runOneReqTest = (path) => {312            // put the first request in flight313            const p1 = this.server._onResolveUrl(`http://localhost:${this.httpPort}/${path}/1000`, {}, this.automationRequest)314            return Promise.delay(100)315            .then(() => {316              // the p1 should not have a current promise phase or reqStream until it's canceled317              expect(p1).not.to.have.property('currentPromisePhase')318              expect(p1).not.to.have.property('reqStream')319              // fire the 2nd request now that the first one has had some time to reach out320              return this.server._onResolveUrl(`http://localhost:${this.httpPort}/${path}/100`, {}, this.automationRequest)321            }).then((obj) => {322              expectToEqDetails(obj, {323                isOkStatusCode: true,324                isHtml: true,325                contentType: 'text/html',326                url: `http://localhost:${this.httpPort}/${path}/100`,327                originalUrl: `http://localhost:${this.httpPort}/${path}/100`,328                status: 200,329                statusText: 'OK',330                redirects: [],331                cookies: [],332              })333              expect(p1.isCancelled()).to.be.true334              expect(p1).to.have.property('currentPromisePhase')335              expect(p1.reqStream.aborted).to.be.true336            })337          }338        })339        it('cancels and aborts the 1st request when it hasn\'t loaded headers and a 2nd request is made', function () {340          return this.runOneReqTest('pause-before-headers')341        })342        it('cancels and aborts the 1st request when it hasn\'t loaded body and a 2nd request is made', function () {343          return this.runOneReqTest('pause-before-body')344        })345      })346      it('can serve http requests', function () {347        nock('http://getbootstrap.com')348        .matchHeader('user-agent', 'foobarbaz')349        .matchHeader('accept', 'text/html,*/*')350        .get('/')351        .reply(200, '<html>content</html>', {352          'X-Foo-Bar': 'true',353          'Content-Type': 'text/html',354          'Cache-Control': 'public, max-age=3600',355        })356        const headers = {}357        headers['user-agent'] = 'foobarbaz'358        return this.server._onResolveUrl('http://getbootstrap.com/', headers, this.automationRequest)359        .then((obj = {}) => {360          return expectToEqDetails(obj, {361            isOkStatusCode: true,362            isHtml: true,363            contentType: 'text/html',364            url: 'http://getbootstrap.com/',365            originalUrl: 'http://getbootstrap.com/',366            status: 200,367            statusText: 'OK',368            redirects: [],369            cookies: [],370          })371        }).then(() => {372          return this.rp('http://getbootstrap.com/')373          .then((res) => {374            expect(res.statusCode).to.eq(200)375            expect(res.headers['set-cookie']).not.to.match(/initial=;/)376            expect(res.headers['x-foo-bar']).to.eq('true')377            expect(res.headers['cache-control']).to.eq('no-cache, no-store, must-revalidate')378            expect(res.body).to.include('content')379            expect(res.body).to.include('document.domain = \'getbootstrap.com\'')380            expect(res.body).to.include('.action("app:window:before:load",window)')381            expect(res.body).to.include('</head>content</html>')382          })383        })384      })385      it('sends back the content type', function () {386        nock('http://getbootstrap.com')387        .get('/user.json')388        .reply(200, {})389        return this.server._onResolveUrl('http://getbootstrap.com/user.json', {}, this.automationRequest)390        .then((obj = {}) => {391          return expectToEqDetails(obj, {392            isOkStatusCode: true,393            isHtml: false,394            contentType: 'application/json',395            url: 'http://getbootstrap.com/user.json',396            originalUrl: 'http://getbootstrap.com/user.json',397            status: 200,398            statusText: 'OK',399            redirects: [],400            cookies: [],401          })402        })403      })404      // @see https://github.com/cypress-io/cypress/issues/8506405      it('yields isHtml true for unconventional HTML content-types', async function () {406        const scope = nock('http://example.com')407        .get('/a').reply(200, 'notHtml')408        .get('/b').reply(200, 'notHtml', { 'content-type': 'Text/Html' })409        .get('/c').reply(200, 'notHtml', { 'content-type': 'text/html;charset=utf-8' })410        // invalid, but let's be tolerant411        .get('/d').reply(200, 'notHtml', { 'content-type': 'text/html;' })412        .get('/e').reply(200, 'notHtml', { 'content-type': 'application/xhtml+xml' })413        const bad = await this.server._onResolveUrl('http://example.com/a', {}, this.automationRequest)414        expect(bad.isHtml).to.be.false415        for (const path of ['/b', '/c', '/d', '/e']) {416          const details = await this.server._onResolveUrl(`http://example.com${path}`, {}, this.automationRequest)417          expect(details.isHtml).to.be.true418        }419        scope.done()420      })421      it('yields isHtml true for HTML-shaped responses', function () {422        nock('http://example.com')423        .get('/')424        .reply(200, '<html>foo</html>')425        return this.server._onResolveUrl('http://example.com', {}, this.automationRequest)426        .then((obj = {}) => {427          return expectToEqDetails(obj, {428            isOkStatusCode: true,429            isHtml: true,430            contentType: undefined,431            url: 'http://example.com/',432            originalUrl: 'http://example.com/',433            status: 200,434            statusText: 'OK',435            redirects: [],436            cookies: [],437          })438        })439      })440      it('yields isHtml false for non-HTML-shaped responses', function () {441        nock('http://example.com')442        .get('/')443        .reply(200, '{ foo: "bar" }')444        return this.server._onResolveUrl('http://example.com', {}, this.automationRequest)445        .then((obj = {}) => {446          return expectToEqDetails(obj, {447            isOkStatusCode: true,448            isHtml: false,449            contentType: undefined,450            url: 'http://example.com/',451            originalUrl: 'http://example.com/',452            status: 200,453            statusText: 'OK',454            redirects: [],455            cookies: [],456          })457        })458      })459      it('can follow multiple http redirects', function () {460        nock('http://espn.com')461        .get('/')462        .reply(301, undefined, {463          'Location': '/foo',464        })465        .get('/foo')466        .reply(302, undefined, {467          'Location': 'http://espn.go.com/',468        })469        nock('http://espn.go.com')470        .get('/')471        .reply(200, '<html>content</html>', {472          'Content-Type': 'text/html',473        })474        return this.server._onResolveUrl('http://espn.com/', {}, this.automationRequest)475        .then((obj = {}) => {476          return expectToEqDetails(obj, {477            isOkStatusCode: true,478            isHtml: true,479            contentType: 'text/html',480            url: 'http://espn.go.com/',481            originalUrl: 'http://espn.com/',482            status: 200,483            statusText: 'OK',484            cookies: [],485            redirects: [486              '301: http://espn.com/foo',487              '302: http://espn.go.com/',488            ],489          })490        }).then(() => {491          return this.rp('http://espn.go.com/')492          .then((res) => {493            expect(res.statusCode).to.eq(200)494            expect(res.body).to.include('content')495            expect(res.body).to.include('document.domain = \'go.com\'')496            expect(res.body).to.include('.action("app:window:before:load",window)')497            expect(res.body).to.include('</head>content</html>')498            expect(this.server._getRemoteState()).to.deep.eq({499              auth: undefined,500              origin: 'http://espn.go.com',501              strategy: 'http',502              visiting: false,503              domainName: 'go.com',504              fileServer: null,505              props: {506                domain: 'go',507                tld: 'com',508                port: '80',509              },510            })511          })512        })513      })514      it('buffers the http response', function () {515        sinon.spy(this.server.request, 'sendStream')516        nock('http://espn.com')517        .get('/')518        .times(2)519        .reply(301, undefined, {520          'Location': '/foo',521        })522        .get('/foo')523        .times(2)524        .reply(302, undefined, {525          'Location': 'http://espn.go.com/',526        })527        nock('http://espn.go.com')528        .get('/')529        .times(2)530        .reply(200, '<html><head></head><body>espn</body></html>', {531          'Content-Type': 'text/html',532        })533        return this.server._onResolveUrl('http://espn.com/', {}, this.automationRequest)534        .then((obj = {}) => {535          expectToEqDetails(obj, {536            isOkStatusCode: true,537            isHtml: true,538            contentType: 'text/html',539            url: 'http://espn.go.com/',540            originalUrl: 'http://espn.com/',541            status: 200,542            statusText: 'OK',543            cookies: [],544            redirects: [545              '301: http://espn.com/foo',546              '302: http://espn.go.com/',547            ],548          })549          expect(this.buffers.buffer).to.include({ url: 'http://espn.go.com/' })550        }).then(() => {551          return this.server._onResolveUrl('http://espn.com/', {}, this.automationRequest)552          .then((obj = {}) => {553            expectToEqDetails(obj, {554              isOkStatusCode: true,555              isHtml: true,556              contentType: 'text/html',557              url: 'http://espn.go.com/',558              originalUrl: 'http://espn.com/',559              status: 200,560              statusText: 'OK',561              cookies: [],562              redirects: [563                '301: http://espn.com/foo',564                '302: http://espn.go.com/',565              ],566            })567            expect(this.server.request.sendStream).to.be.calledTwice568          })569        }).then(() => {570          return this.rp('http://espn.go.com/')571          .then((res) => {572            expect(res.statusCode).to.eq(200)573            expect(res.body).to.include('document.domain')574            expect(res.body).to.include('go.com')575            expect(res.body).to.include('.action("app:window:before:load",window)')576            expect(res.body).to.include('</script></head><body>espn</body></html>')577            expect(this.buffers.buffer).to.be.undefined578          })579        })580      })581      it('does not buffer \'bad\' responses', function () {582        sinon.spy(this.server.request, 'sendStream')583        nock('http://espn.com')584        .get('/')585        .reply(404, undefined)586        .get('/')587        .reply(301, undefined, {588          'Location': '/foo',589        })590        .get('/foo')591        .reply(301, undefined, {592          'Location': 'http://espn.go.com/',593        })594        nock('http://espn.go.com')595        .get('/')596        .reply(200, 'content', {597          'Content-Type': 'text/html',598        })599        return this.server._onResolveUrl('http://espn.com/', {}, this.automationRequest)600        .then((obj = {}) => {601          expectToEqDetails(obj, {602            isOkStatusCode: false,603            isHtml: false,604            contentType: undefined,605            url: 'http://espn.com/',606            originalUrl: 'http://espn.com/',607            status: 404,608            statusText: 'Not Found',609            cookies: [],610            redirects: [],611          })612          return this.server._onResolveUrl('http://espn.com/', {}, this.automationRequest)613          .then((obj = {}) => {614            expectToEqDetails(obj, {615              isOkStatusCode: true,616              isHtml: true,617              contentType: 'text/html',618              url: 'http://espn.go.com/',619              originalUrl: 'http://espn.com/',620              status: 200,621              statusText: 'OK',622              cookies: [],623              redirects: [624                '301: http://espn.com/foo',625                '301: http://espn.go.com/',626              ],627            })628            expect(this.server.request.sendStream).to.be.calledTwice629          })630        })631      })632      it('gracefully handles 500', function () {633        nock('http://mlb.com')634        .get('/')635        .reply(307, undefined, {636          'Location': 'http://mlb.mlb.com/',637        })638        nock('http://mlb.mlb.com')639        .get('/')640        .reply(500, undefined, {641          'Content-Type': 'text/html',642        })643        return this.server._onResolveUrl('http://mlb.com/', {}, this.automationRequest)644        .then((obj = {}) => {645          return expectToEqDetails(obj, {646            isOkStatusCode: false,647            isHtml: true,648            contentType: 'text/html',649            url: 'http://mlb.mlb.com/',650            originalUrl: 'http://mlb.com/',651            status: 500,652            statusText: 'Internal Server Error',653            cookies: [],654            redirects: ['307: http://mlb.mlb.com/'],655          })656        })657      })658      it('gracefully handles http errors', function () {659        return this.server._onResolveUrl('http://localhost:64646', {}, this.automationRequest)660        .catch((err) => {661          expect(err.message).to.eq('connect ECONNREFUSED 127.0.0.1:64646')662          expect(err.port).to.eq(64646)663          expect(err.code).to.eq('ECONNREFUSED')664        })665      })666      it('handles url hashes', function () {667        nock('http://getbootstrap.com')668        .get('/')669        .reply(200, 'content page', {670          'Content-Type': 'text/html',671        })672        return this.server._onResolveUrl('http://getbootstrap.com/#/foo', {}, this.automationRequest)673        .then((obj = {}) => {674          expectToEqDetails(obj, {675            isOkStatusCode: true,676            isHtml: true,677            contentType: 'text/html',678            url: 'http://getbootstrap.com/',679            originalUrl: 'http://getbootstrap.com/',680            status: 200,681            statusText: 'OK',682            redirects: [],683            cookies: [],684          })685          expect(this.buffers.buffer).to.include({ url: 'http://getbootstrap.com/' })686        }).then(() => {687          return this.rp('http://getbootstrap.com/')688          .then((res) => {689            expect(res.statusCode).to.eq(200)690            expect(this.buffers.buffer).to.be.undefined691          })692        })693      })694      it('can serve non 2xx status code requests when option set', function () {695        nock('http://google.com')696        .matchHeader('user-agent', 'foobarbaz')697        .matchHeader('accept', 'text/html,*/*')698        .get('/foo')699        .reply(404, '<html>content</html>', {700          'X-Foo-Bar': 'true',701          'Content-Type': 'text/html',702          'Cache-Control': 'public, max-age=3600',703        })704        const headers = {}705        headers['user-agent'] = 'foobarbaz'706        return this.server._onResolveUrl('http://google.com/foo', headers, this.automationRequest, { failOnStatusCode: false })707        .then((obj = {}) => {708          return expectToEqDetails(obj, {709            isOkStatusCode: true,710            isHtml: true,711            contentType: 'text/html',712            url: 'http://google.com/foo',713            originalUrl: 'http://google.com/foo',714            status: 404,715            statusText: 'Not Found',716            redirects: [],717            cookies: [],718          })719        }).then(() => {720          return this.rp('http://google.com/foo')721          .then((res) => {722            expect(res.statusCode).to.eq(404)723            expect(res.headers['set-cookie']).not.to.match(/initial=;/)724            expect(res.headers['x-foo-bar']).to.eq('true')725            expect(res.headers['cache-control']).to.eq('no-cache, no-store, must-revalidate')726            expect(res.body).to.include('content')727            expect(res.body).to.include('document.domain = \'google.com\'')728            expect(res.body).to.include('.action("app:window:before:load",window)')729            expect(res.body).to.include('</head>content</html>')730          })731        })732      })733      it('passes auth through', function () {734        const username = 'u'735        const password = 'p'736        const base64 = Buffer.from(`${username}:${password}`).toString('base64')737        const auth = {738          username,739          password,740        }741        nock('http://google.com')742        .get('/index')743        .matchHeader('authorization', `Basic ${base64}`)744        .reply(200, '<html>content</html>', {745          'Content-Type': 'text/html',746        })747        .get('/index2')748        .matchHeader('authorization', `Basic ${base64}`)749        .reply(200, '<html>content</html>', {750          'Content-Type': 'text/html',751        })752        const headers = {}753        headers['user-agent'] = 'foobarbaz'754        return this.server._onResolveUrl('http://google.com/index', headers, this.automationRequest, { auth })755        .then((obj = {}) => {756          return expectToEqDetails(obj, {757            isOkStatusCode: true,758            isHtml: true,759            contentType: 'text/html',760            url: 'http://google.com/index',761            originalUrl: 'http://google.com/index',762            status: 200,763            statusText: 'OK',764            redirects: [],765            cookies: [],766          })767        }).then(() => {768          return this.rp('http://google.com/index2')769          .then((res) => {770            expect(res.statusCode).to.eq(200)771          })772        }).then(() => {773          expect(this.server._getRemoteState()).to.deep.eq({774            auth,775            origin: 'http://google.com',776            strategy: 'http',777            visiting: false,778            domainName: 'google.com',779            fileServer: null,780            props: {781              domain: 'google',782              tld: 'com',783              port: '80',784            },785          })786        })787      })788    })789    describe('both', () => {790      beforeEach(function () {791        Fixtures.scaffold('no-server')792        return this.setup({793          projectRoot: Fixtures.projectPath('no-server'),794          config: {795            port: 2000,796            fileServerFolder: 'dev',797          },798        })799      })800      it('can go from file -> http -> file', function () {801        nock('http://www.google.com')802        .get('/')803        .reply(200, 'content page', {804          'Content-Type': 'text/html',805        })806        return this.server._onResolveUrl('/index.html', {}, this.automationRequest)807        .then((obj = {}) => {808          return expectToEqDetails(obj, {809            isOkStatusCode: true,810            isHtml: true,811            contentType: 'text/html',812            url: 'http://localhost:2000/index.html',813            originalUrl: '/index.html',814            filePath: Fixtures.projectPath('no-server/dev/index.html'),815            status: 200,816            statusText: 'OK',817            redirects: [],818            cookies: [],819          })820        }).then(() => {821          return this.rp('http://localhost:2000/index.html')822          .then((res) => {823            expect(res.statusCode).to.eq(200)824          })825        }).then(() => {826          return this.server._onResolveUrl('http://www.google.com/', {}, this.automationRequest)827        }).then((obj = {}) => {828          return expectToEqDetails(obj, {829            isOkStatusCode: true,830            isHtml: true,831            contentType: 'text/html',832            url: 'http://www.google.com/',833            originalUrl: 'http://www.google.com/',834            status: 200,835            statusText: 'OK',836            redirects: [],837            cookies: [],838          })839        }).then(() => {840          return this.rp('http://www.google.com/')841          .then((res) => {842            expect(res.statusCode).to.eq(200)843          })844        }).then(() => {845          expect(this.server._getRemoteState()).to.deep.eq({846            auth: undefined,847            origin: 'http://www.google.com',848            strategy: 'http',849            visiting: false,850            domainName: 'google.com',851            fileServer: null,852            props: {853              domain: 'google',854              tld: 'com',855              port: '80',856            },857          })858        }).then(() => {859          return this.server._onResolveUrl('/index.html', {}, this.automationRequest)860          .then((obj = {}) => {861            return expectToEqDetails(obj, {862              isOkStatusCode: true,863              isHtml: true,864              contentType: 'text/html',865              url: 'http://localhost:2000/index.html',866              originalUrl: '/index.html',867              filePath: Fixtures.projectPath('no-server/dev/index.html'),868              status: 200,869              statusText: 'OK',870              redirects: [],871              cookies: [],872            })873          })874        }).then(() => {875          return this.rp('http://localhost:2000/index.html')876          .then((res) => {877            expect(res.statusCode).to.eq(200)878          })879        }).then(() => {880          expect(this.server._getRemoteState()).to.deep.eq({881            auth: undefined,882            origin: 'http://localhost:2000',883            strategy: 'file',884            visiting: false,885            domainName: 'localhost',886            fileServer: this.fileServer,887            props: null,888          })889        })890      })891      it('can go from http -> file -> http', function () {892        nock('http://www.google.com')893        .get('/')894        .reply(200, '<html><head></head><body>google</body></html>', {895          'Content-Type': 'text/html',896        })897        .get('/')898        .reply(200, '<html><head></head><body>google</body></html>', {899          'Content-Type': 'text/html',900        })901        return this.server._onResolveUrl('http://www.google.com/', {}, this.automationRequest)902        .then((obj = {}) => {903          return expectToEqDetails(obj, {904            isOkStatusCode: true,905            isHtml: true,906            contentType: 'text/html',907            url: 'http://www.google.com/',908            originalUrl: 'http://www.google.com/',909            status: 200,910            statusText: 'OK',911            redirects: [],912            cookies: [],913          })914        }).then(() => {915          return this.rp('http://www.google.com/')916          .then((res) => {917            expect(res.statusCode).to.eq(200)918            expect(res.body).to.include('document.domain')919            expect(res.body).to.include('google.com')920            expect(res.body).to.include('.action("app:window:before:load",window)')921            expect(res.body).to.include('</script></head><body>google</body></html>')922          })923        }).then(() => {924          expect(this.server._getRemoteState()).to.deep.eq({925            auth: undefined,926            origin: 'http://www.google.com',927            strategy: 'http',928            visiting: false,929            domainName: 'google.com',930            fileServer: null,931            props: {932              domain: 'google',933              tld: 'com',934              port: '80',935            },936          })937        }).then(() => {938          return this.server._onResolveUrl('/index.html', {}, this.automationRequest)939          .then((obj = {}) => {940            return expectToEqDetails(obj, {941              isOkStatusCode: true,942              isHtml: true,943              contentType: 'text/html',944              url: 'http://localhost:2000/index.html',945              originalUrl: '/index.html',946              filePath: Fixtures.projectPath('no-server/dev/index.html'),947              status: 200,948              statusText: 'OK',949              redirects: [],950              cookies: [],951            })952          })953        }).then(() => {954          return this.rp('http://localhost:2000/index.html')955          .then((res) => {956            expect(res.statusCode).to.eq(200)957            expect(res.body).to.include('document.domain')958            expect(res.body).to.include('localhost')959            expect(res.body).to.include('.action("app:window:before:load",window)')960          })961        }).then(() => {962          expect(this.server._getRemoteState()).to.deep.eq({963            auth: undefined,964            origin: 'http://localhost:2000',965            strategy: 'file',966            visiting: false,967            domainName: 'localhost',968            fileServer: this.fileServer,969            props: null,970          })971        }).then(() => {972          return this.server._onResolveUrl('http://www.google.com/', {}, this.automationRequest)973          .then((obj = {}) => {974            return expectToEqDetails(obj, {975              isOkStatusCode: true,976              isHtml: true,977              contentType: 'text/html',978              url: 'http://www.google.com/',979              originalUrl: 'http://www.google.com/',980              status: 200,981              statusText: 'OK',982              redirects: [],983              cookies: [],984            })985          }).then(() => {986            return this.rp('http://www.google.com/')987            .then((res) => {988              expect(res.statusCode).to.eq(200)989              expect(res.body).to.include('document.domain')990              expect(res.body).to.include('google.com')991              expect(res.body).to.include('.action("app:window:before:load",window)')992              expect(res.body).to.include('</script></head><body>google</body></html>')993            })994          }).then(() => {995            expect(this.server._getRemoteState()).to.deep.eq({996              auth: undefined,997              origin: 'http://www.google.com',998              strategy: 'http',999              visiting: false,1000              domainName: 'google.com',1001              fileServer: null,1002              props: {1003                domain: 'google',1004                tld: 'com',1005                port: '80',1006              },1007            })1008          })1009        })1010      })1011      it('can go from https -> file -> https', function () {1012        evilDns.add('*.foobar.com', '127.0.0.1')1013        return this.server._onResolveUrl('https://www.foobar.com:8443/', {}, this.automationRequest)1014        .then((obj = {}) => {1015          return expectToEqDetails(obj, {1016            isOkStatusCode: true,1017            isHtml: true,1018            contentType: 'text/html',1019            url: 'https://www.foobar.com:8443/',1020            originalUrl: 'https://www.foobar.com:8443/',1021            status: 200,1022            statusText: 'OK',1023            redirects: [],1024            cookies: [],1025          })1026        }).then(() => {1027          return this.rp('https://www.foobar.com:8443/')1028          .then((res) => {1029            expect(res.statusCode).to.eq(200)1030            expect(res.body).to.include('document.domain')1031            expect(res.body).to.include('foobar.com')1032            expect(res.body).to.include('.action("app:window:before:load",window)')1033            expect(res.body).to.include('</script></head><body>https server</body></html>')1034          })1035        }).then(() => {1036          expect(this.server._getRemoteState()).to.deep.eq({1037            auth: undefined,1038            origin: 'https://www.foobar.com:8443',1039            strategy: 'http',1040            visiting: false,1041            domainName: 'foobar.com',1042            fileServer: null,1043            props: {1044              domain: 'foobar',1045              tld: 'com',1046              port: '8443',1047            },1048          })1049        }).then(() => {1050          return this.server._onResolveUrl('/index.html', {}, this.automationRequest)1051          .then((obj = {}) => {1052            return expectToEqDetails(obj, {1053              isOkStatusCode: true,1054              isHtml: true,1055              contentType: 'text/html',1056              url: 'http://localhost:2000/index.html',1057              originalUrl: '/index.html',1058              filePath: Fixtures.projectPath('no-server/dev/index.html'),1059              status: 200,1060              statusText: 'OK',1061              redirects: [],1062              cookies: [],1063            })1064          })1065        }).then(() => {1066          return this.rp('http://localhost:2000/index.html')1067          .then((res) => {1068            expect(res.statusCode).to.eq(200)1069            expect(res.body).to.include('document.domain')1070            expect(res.body).to.include('localhost')1071            expect(res.body).to.include('.action("app:window:before:load",window)')1072          })1073        }).then(() => {1074          expect(this.server._getRemoteState()).to.deep.eq({1075            auth: undefined,1076            origin: 'http://localhost:2000',1077            strategy: 'file',1078            visiting: false,1079            domainName: 'localhost',1080            fileServer: this.fileServer,1081            props: null,1082          })1083        }).then(() => {1084          return this.server._onResolveUrl('https://www.foobar.com:8443/', {}, this.automationRequest)1085          .then((obj = {}) => {1086            return expectToEqDetails(obj, {1087              isOkStatusCode: true,1088              isHtml: true,1089              contentType: 'text/html',1090              url: 'https://www.foobar.com:8443/',1091              originalUrl: 'https://www.foobar.com:8443/',1092              status: 200,1093              statusText: 'OK',1094              redirects: [],1095              cookies: [],1096            })1097          }).then(() => {1098            return this.rp('https://www.foobar.com:8443/')1099            .then((res) => {1100              expect(res.statusCode).to.eq(200)1101              expect(res.body).to.include('document.domain')1102              expect(res.body).to.include('foobar.com')1103              expect(res.body).to.include('.action("app:window:before:load",window)')1104              expect(res.body).to.include('</script></head><body>https server</body></html>')1105            })1106          }).then(() => {1107            expect(this.server._getRemoteState()).to.deep.eq({1108              auth: undefined,1109              origin: 'https://www.foobar.com:8443',1110              strategy: 'http',1111              visiting: false,1112              fileServer: null,1113              domainName: 'foobar.com',1114              props: {1115                domain: 'foobar',1116                tld: 'com',1117                port: '8443',1118              },1119            })1120          })1121        })1122      })1123      it('can go from https -> file -> https without a port', function () {1124        this.timeout(5000)1125        return this.server._onResolveUrl(s3StaticHtmlUrl, {}, this.automationRequest)1126        .then((obj = {}) => {1127          return expectToEqDetails(obj, {1128            isOkStatusCode: true,1129            isHtml: true,1130            contentType: 'text/html',1131            url: s3StaticHtmlUrl,1132            originalUrl: s3StaticHtmlUrl,1133            status: 200,1134            statusText: 'OK',1135            redirects: [],1136            cookies: [],1137          })1138        }).then(() => {1139          // @server.onRequest (req, res) ->1140          //   console.log "ON REQUEST!!!!!!!!!!!!!!!!!!!!!!"1141          //   nock("https://s3.amazonaws.com")1142          //   .get("/internal-test-runner-assets.cypress.io/index.html")1143          //   .reply 200, "<html><head></head><body>jsonplaceholder</body></html>", {1144          //     "Content-Type": "text/html"1145          //   }1146          return this.rp(s3StaticHtmlUrl)1147          .then((res) => {1148            expect(res.statusCode).to.eq(200)1149            expect(res.body).to.include('document.domain')1150            expect(res.body).to.include('amazonaws.com')1151            expect(res.body).to.include('Cypress')1152          })1153        }).then(() => {1154          expect(this.server._getRemoteState()).to.deep.eq({1155            auth: undefined,1156            origin: 'https://s3.amazonaws.com',1157            strategy: 'http',1158            visiting: false,1159            domainName: 's3.amazonaws.com',1160            fileServer: null,1161            props: {1162              domain: '',1163              tld: 's3.amazonaws.com',1164              port: '443',1165            },1166          })1167        }).then(() => {1168          return this.server._onResolveUrl('/index.html', {}, this.automationRequest)1169          .then((obj = {}) => {1170            return expectToEqDetails(obj, {1171              isOkStatusCode: true,1172              isHtml: true,1173              contentType: 'text/html',1174              url: 'http://localhost:2000/index.html',1175              originalUrl: '/index.html',1176              filePath: Fixtures.projectPath('no-server/dev/index.html'),1177              status: 200,1178              statusText: 'OK',1179              redirects: [],1180              cookies: [],1181            })1182          })1183        }).then(() => {1184          return this.rp('http://localhost:2000/index.html')1185          .then((res) => {1186            expect(res.statusCode).to.eq(200)1187            expect(res.body).to.include('document.domain')1188            expect(res.body).to.include('localhost')1189            expect(res.body).to.include('.action("app:window:before:load",window)')1190          })1191        }).then(() => {1192          expect(this.server._getRemoteState()).to.deep.eq({1193            auth: undefined,1194            origin: 'http://localhost:2000',1195            strategy: 'file',1196            visiting: false,1197            domainName: 'localhost',1198            fileServer: this.fileServer,1199            props: null,1200          })1201        }).then(() => {1202          return this.server._onResolveUrl(s3StaticHtmlUrl, {}, this.automationRequest)1203          .then((obj = {}) => {1204            return expectToEqDetails(obj, {1205              isOkStatusCode: true,1206              isHtml: true,1207              contentType: 'text/html',1208              url: s3StaticHtmlUrl,1209              originalUrl: s3StaticHtmlUrl,1210              status: 200,1211              statusText: 'OK',1212              redirects: [],1213              cookies: [],1214            })1215          }).then(() => {1216            // @server.onNextRequest (req, res) ->...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { resolveUrl } from 'cypress-real-events/support'2describe('test', () => {3  it('test', () => {4    cy.get('input[name="q"]').type('test')5    cy.get('input[name="q"]').type('{enter}')6    cy.get('a[href="/search?q=test&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiu6Jn5w7LsAhXjKX0KHUHlB9cQ_AUoAXoECB8QAw&biw=1536&bih=754"]')7      .click()8    cy.get('.rg_i.Q4LuWd')9      .eq(0)10      .then(($el) => {11        const src = $el.attr('src')12        cy.log(src)13        const url = resolveUrl(src)14        cy.log(url)15        cy.visit(url)16      })17  })18})19const url = resolveUrl(src)20I have also tried using cy.visit(url) instead of cy.get('.rg_i.Q4LuWd') and it works fine. I am not sure what I am doing wrong. Can someone help me with this?21cy.get('input[name="q"]').type('test')22cy.get('input[name="q"]').type('{enter}')23cy.get('input[name="q"]').type('test{enter}')24cy.get('input[name="q"]').type('test')25cy.get('input[name="q"]').type('{enter}')26cy.get('input[name="q"]').type('test')27cy.get('input[name="q"]').type('{enter}')

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('uploadFile', (fixturePath, fileName, mimeType) => {2    cy.fixture(fixturePath, 'base64').then(content => {3        cy.get('input[type="file"]').upload({4        });5    });6});7import 'cypress-file-upload';8import '@testing-library/cypress/add-commands';9import 'cypress-wait-until';10import 'cypress-iframe';11import 'cypress-xpath';12import './commands';13Cypress.on('uncaught:exception', (err, runnable) => {14    return false;15});16{17    "env": {18    }19}20const fs = require('fs-extra');21const path = require('path');22const webpackPreprocessor = require('@cypress/webpack-preprocessor');23const webpackConfig = require('../../webpack.config.js');24const wpOptions = {25    watchOptions: {}26};27module.exports = (on, config) => {28    on('file:preprocessor', webpackPreprocessor(wpOptions));29    on('task', {30        log(message) {31            console.log(message);32            return null;33        },34        table(message) {35            console.table(message);36            return null;37        },38        clearCookies() {39            return new Promise((resolve, reject) => {40                fs.remove(path.join(__dirname, '..', '..', 'cypress', 'cookies.json'), err => {41                    if (err) {42                        return reject(err);43                    }44                    resolve(null);45                });46            });47        }48    });49};50import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command';51addMatchImageSnapshotCommand({

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2module.exports = (on, config) => {3  on('file:preprocessor', (file) => {4    const filePath = file.filePath.replace(/cypress[\\\/]integration[\\\/]/, '');5    return require('@cypress/webpack-preprocessor')({6      webpackOptions: {7        resolve: {8          alias: {9            '@': path.resolve('src'),10          },11        },12        module: {13            {14                {15                  options: {16                  },17                },18            },19        },20      },21      watchOptions: {},22    })(file);23  });24};25Cypress.Commands.add('resolveUrl', (url) => {26  return cy.server()._onResolveUrl(url);27});28describe('My First Test', () => {29  it('Visits the Kitchen Sink', () => {30    cy.visit(Cypress.env('baseUrl'));31    cy.get('a').contains('Home').click();32    cy.url().should('include', Cypress.env('baseUrl'));33  });34});35{

Full Screen

Using AI Code Generation

copy

Full Screen

1const win = window as any;2const url = win.Cypress.server._onResolveUrl('/assets/logo.png');3console.log(url);4const win = window as any;5const url = win.Cypress.server._onResolveUrl('/assets/logo.png');6console.log(url);7Cypress.Commands.add('visitPage', (path: string) => {8  cy.visit(path);9  cy.get('h1').should('be.visible');10  cy.get('h1').should('contain', 'Home');11});12Cypress.Commands.add('visitPage', (path: string) => {13  cy.visit(path);14  cy.get('h1').should('be.visible');15  cy.get('h1').should('contain', 'Home');16});17Cypress.Commands.add('visitPage', (path: string) => {18  cy.visit(path);19  cy.get('h1').should('be.visible');20  cy.get('h1').should('contain', 'Home');21});22Cypress.Commands.add('visitPage', (path: string) => {23  cy.visit(path);24  cy.get('h1').should('be.visible');25  cy.get('h1').should('contain', 'Home');26});27Cypress.Commands.add('visitPage', (path: string) => {28  cy.visit(path);29  cy.get('h1').should('be.visible');30  cy.get('h1').should('contain', 'Home');31});32Cypress.Commands.add('visitPage', (path: string) => {33  cy.visit(path);34  cy.get('h1').should('be.visible');35  cy.get('h1').should('contain', 'Home');36});37Cypress.Commands.add('visitPage', (path: string) => {38  cy.visit(path);39  cy.get('h1').should('be.visible');40  cy.get('h1').should('contain', 'Home');41});42Cypress.Commands.add('visitPage', (path: string) => {43  cy.visit(path);44  cy.get('h1').should('be.visible');45  cy.get('h1').should('contain', 'Home');46});47Cypress.Commands.add('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2  it('test', () => {3    cy.server();4    cy.route({5    }).as('getUsers');6    cy.visit('/');7    cy.wait('@getUsers');8    cy.get('[data-test="user"]').should('have.length', 2);9  });10});11Cypress.Commands.add('interceptRequest', (url, response) => {12  cy.intercept(url, response);13});14describe('Test', () => {15  it('test', () => {16    cy.server();17    cy.route({18    }).as('getUsers');19    cy.visit('/');20    cy.wait('@getUsers');21    cy.get('[data-test="user"]').should('have.length', 2);22  });23});24Cypress.Commands.add('interceptRequest', (url, response

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("getTestData", (url) => {2  cy.server();3  cy.route(url).as("getTestData");4  cy.wait("@getTestData").then((xhr) => {5    cy.wrap(xhr.response.body).as("testData");6  });7});8describe("Test", () => {9  it("should get data and use it in the test", () => {10    cy.getTestData("/test.json");11    cy.get("@testData").then((data) => {12      cy.log(data);13    });14  });15});16Cypress.Commands.add("getTestData", (url) => {17  cy.server();18  cy.route(url).as("getTestData");19  cy.wait("@getTestData").then((xhr) => {20    cy.wrap(xhr.response.body).as("testData");21  });22});23Cypress.Commands.add("getTestData", (url) => {24  cy.server();25  cy.route(url).as("getTestData");26  cy.wait("@getTestData").then((xhr) => {27    cy.wrap(xhr.response.body).as("testData");28  });29});30describe("Test", () => {31  it("should get data and use it in the test", () => {32    cy.getTestData("/test.json");33    cy.get("@testData").then((data) => {34      cy.log(data);35    });36  });37});38Cypress.Commands.add("getTestData", (url) => {39  cy.server();40  cy.route(url).as("getTestData");41  cy.wait("@getTestData").then((xhr) => {42    cy.wrap(xhr.response.body).as("testData");43  });44});45Cypress.Commands.add("getTestData", (url) => {46  cy.server();47  cy.route(url).as("getTestData");48  cy.wait("@getTestData").then((xhr) => {49    cy.wrap(xhr.response.body).as("testData");50  });51});52Cypress.Commands.add("getTestData", (url) => {53  cy.server();

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful