Best JavaScript code snippet using cypress
cookies_spec.js
Source:cookies_spec.js
1const { stripIndent } = require('common-tags')2const { Promise } = Cypress3describe('src/cy/commands/cookies', () => {4 beforeEach(() => {5 // call through normally on everything6 cy.stub(Cypress, 'automation').rejects(new Error('Cypress.automation was not stubbed'))7 })8 context('test:before:run:async', () => {9 it('clears cookies before each test run', () => {10 Cypress.automation11 .withArgs('get:cookies', { domain: 'localhost' })12 .resolves([{ name: 'foo' }])13 .withArgs('clear:cookies', [{ domain: 'localhost', name: 'foo' }])14 .resolves([])15 Cypress.emitThen('test:before:run:async', {})16 .then(() => {17 expect(Cypress.automation).to.be.calledWith(18 'get:cookies',19 { domain: 'localhost' },20 )21 expect(Cypress.automation).to.be.calledWith(22 'clear:cookies',23 [{ domain: 'localhost', name: 'foo' }],24 )25 })26 })27 it('does not call clear:cookies when get:cookies returns empty array', () => {28 Cypress.automation.withArgs('get:cookies').resolves([])29 Cypress.emitThen('test:before:run:async', {})30 .then(() => {31 expect(Cypress.automation).not.to.be.calledWith(32 'clear:cookies',33 )34 })35 })36 it('does not attempt to time out', () => {37 Cypress.automation38 .withArgs('get:cookies', { domain: 'localhost' })39 .resolves([{ name: 'foo' }])40 .withArgs('clear:cookies', [{ domain: 'localhost', name: 'foo' }])41 .resolves([])42 const timeout = cy.spy(Promise.prototype, 'timeout')43 Cypress.emitThen('test:before:run:async', {})44 .then(() => {45 expect(timeout).not.to.be.called46 })47 })48 })49 context('#getCookies', () => {50 it('returns array of cookies', () => {51 Cypress.automation.withArgs('get:cookies').resolves([])52 cy.getCookies().should('deep.eq', []).then(() => {53 expect(Cypress.automation).to.be.calledWith(54 'get:cookies',55 { domain: 'localhost' },56 )57 })58 })59 describe('timeout', () => {60 it('sets timeout to Cypress.config(responseTimeout)', {61 responseTimeout: 2500,62 }, () => {63 Cypress.automation.resolves([])64 const timeout = cy.spy(Promise.prototype, 'timeout')65 cy.getCookies().then(() => {66 expect(timeout).to.be.calledWith(2500)67 })68 })69 it('can override timeout', () => {70 Cypress.automation.resolves([])71 const timeout = cy.spy(Promise.prototype, 'timeout')72 cy.getCookies({ timeout: 1000 }).then(() => {73 expect(timeout).to.be.calledWith(1000)74 })75 })76 it('clears the current timeout and restores after success', () => {77 Cypress.automation.resolves([])78 cy.timeout(100)79 cy.spy(cy, 'clearTimeout')80 cy.getCookies().then(() => {81 expect(cy.clearTimeout).to.be.calledWith('get:cookies')82 // restores the timeout afterwards83 expect(cy.timeout()).to.eq(100)84 })85 })86 })87 describe('errors', {88 defaultCommandTimeout: 50,89 }, () => {90 beforeEach(function () {91 this.logs = []92 cy.on('log:added', (attrs, log) => {93 if (attrs.name === 'getCookies') {94 this.lastLog = log95 this.logs.push(log)96 }97 })98 return null99 })100 it('logs once on error', function (done) {101 const error = new Error('some err message')102 error.name = 'foo'103 error.stack = 'stack'104 Cypress.automation.rejects(error)105 cy.on('fail', () => {106 const { lastLog } = this107 expect(this.logs.length).to.eq(1)108 expect(lastLog.get('error').message).to.contain(`\`cy.getCookies()\` had an unexpected error reading cookies from ${Cypress.browser.displayName}.`)109 expect(lastLog.get('error').message).to.contain('some err message')110 done()111 })112 cy.getCookies()113 })114 it('throws after timing out', function (done) {115 Cypress.automation.resolves(Promise.delay(1000))116 cy.on('fail', (err) => {117 const { lastLog } = this118 expect(this.logs.length).to.eq(1)119 expect(lastLog.get('error')).to.eq(err)120 expect(lastLog.get('state')).to.eq('failed')121 expect(lastLog.get('name')).to.eq('getCookies')122 expect(lastLog.get('message')).to.eq('')123 expect(err.message).to.eq('`cy.getCookies()` timed out waiting `50ms` to complete.')124 expect(err.docsUrl).to.eq('https://on.cypress.io/getcookies')125 done()126 })127 cy.getCookies({ timeout: 50 })128 })129 })130 describe('.log', () => {131 beforeEach(function () {132 cy.on('log:added', (attrs, log) => {133 if (attrs.name === 'getCookies') {134 this.lastLog = log135 }136 })137 Cypress.automation138 .withArgs('get:cookies', { domain: 'localhost' })139 .resolves([140 { name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false },141 ])142 })143 it('can turn off logging', () => {144 cy.getCookies({ log: false }).then(function () {145 expect(this.lastLog).to.be.undefined146 })147 })148 it('ends immediately', () => {149 cy.getCookies().then(function () {150 const { lastLog } = this151 expect(lastLog.get('ended')).to.be.true152 expect(lastLog.get('state')).to.eq('passed')153 })154 })155 it('snapshots immediately', () => {156 cy.getCookies().then(function () {157 const { lastLog } = this158 expect(lastLog.get('snapshots').length).to.eq(1)159 expect(lastLog.get('snapshots')[0]).to.be.an('object')160 })161 })162 it('#consoleProps', () => {163 cy.getCookies().then(function (cookies) {164 expect(cookies).to.deep.eq([{ name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false }])165 const c = this.lastLog.invoke('consoleProps')166 expect(c['Yielded']).to.deep.eq(cookies)167 expect(c['Num Cookies']).to.eq(1)168 })169 })170 })171 })172 context('#getCookie', () => {173 it('returns single cookie by name', () => {174 Cypress.automation.withArgs('get:cookie').resolves({175 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false,176 })177 cy.getCookie('foo').should('deep.eq', {178 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false,179 })180 .then(() => {181 expect(Cypress.automation).to.be.calledWith(182 'get:cookie',183 { domain: 'localhost', name: 'foo' },184 )185 })186 })187 it('returns null when no cookie was found', () => {188 Cypress.automation.withArgs('get:cookie').resolves(null)189 cy.getCookie('foo').should('be.null')190 })191 describe('timeout', () => {192 it('sets timeout to Cypress.config(responseTimeout)', {193 responseTimeout: 2500,194 }, () => {195 Cypress.automation.resolves(null)196 const timeout = cy.spy(Promise.prototype, 'timeout')197 cy.getCookie('foo').then(() => {198 expect(timeout).to.be.calledWith(2500)199 })200 })201 it('can override timeout', () => {202 Cypress.automation.resolves(null)203 const timeout = cy.spy(Promise.prototype, 'timeout')204 cy.getCookie('foo', { timeout: 1000 }).then(() => {205 expect(timeout).to.be.calledWith(1000)206 })207 })208 it('clears the current timeout and restores after success', () => {209 Cypress.automation.resolves(null)210 cy.timeout(100)211 cy.spy(cy, 'clearTimeout')212 cy.getCookie('foo').then(() => {213 expect(cy.clearTimeout).to.be.calledWith('get:cookie')214 // restores the timeout afterwards215 expect(cy.timeout()).to.eq(100)216 })217 })218 })219 describe('errors', {220 defaultCommandTimeout: 100,221 }, () => {222 beforeEach(function () {223 this.logs = []224 cy.on('log:added', (attrs, log) => {225 if (attrs.name === 'getCookie') {226 this.lastLog = log227 this.logs.push(log)228 }229 })230 return null231 })232 it('logs once on error', function (done) {233 const error = new Error('some err message')234 error.name = 'foo'235 error.stack = 'stack'236 Cypress.automation.rejects(error)237 cy.on('fail', (err) => {238 const { lastLog } = this239 expect(this.logs.length).to.eq(1)240 expect(lastLog.get('error').message).to.contain(`\`cy.getCookie()\` had an unexpected error reading the requested cookie from ${Cypress.browser.displayName}.`)241 expect(lastLog.get('error').message).to.contain('some err message')242 done()243 })244 cy.getCookie('foo')245 })246 it('throws after timing out', function (done) {247 Cypress.automation.resolves(Promise.delay(1000))248 cy.on('fail', (err) => {249 const { lastLog } = this250 expect(this.logs.length).to.eq(1)251 expect(lastLog.get('error')).to.eq(err)252 expect(lastLog.get('state')).to.eq('failed')253 expect(lastLog.get('name')).to.eq('getCookie')254 expect(lastLog.get('message')).to.eq('foo')255 expect(err.message).to.eq('`cy.getCookie()` timed out waiting `50ms` to complete.')256 expect(err.docsUrl).to.eq('https://on.cypress.io/getcookie')257 done()258 })259 cy.getCookie('foo', { timeout: 50 })260 })261 it('requires a string name', function (done) {262 cy.on('fail', (err) => {263 const { lastLog } = this264 expect(this.logs.length).to.eq(1)265 expect(lastLog.get('error').message).to.eq('`cy.getCookie()` must be passed a string argument for name.')266 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/getcookie')267 expect(lastLog.get('error')).to.eq(err)268 done()269 })270 cy.getCookie(123)271 })272 })273 describe('.log', () => {274 beforeEach(function () {275 this.asserts = []276 cy.on('log:added', (attrs, log) => {277 if (attrs.name === 'getCookie') {278 this.lastLog = log279 }280 if (attrs.name === 'assert') {281 this.asserts.push(log)282 }283 })284 Cypress.automation285 .withArgs('get:cookie', { domain: 'localhost', name: 'foo' })286 .resolves({287 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false,288 })289 .withArgs('get:cookie', { domain: 'localhost', name: 'bar' })290 .resolves(null)291 })292 it('can turn off logging', () => {293 cy.getCookie('foo', { log: false }).then(function () {294 expect(this.log).to.be.undefined295 })296 })297 it('only logs assertion once when should is invoked', () => {298 cy.getCookie('foo').should('exist').then(function () {299 expect(this.asserts.length).to.eq(1)300 })301 })302 it('ends immediately', () => {303 cy.getCookie('foo').then(function () {304 const { lastLog } = this305 expect(lastLog.get('ended')).to.be.true306 expect(lastLog.get('state')).to.eq('passed')307 })308 })309 it('has correct message', () => {310 cy.getCookie('foo').then(function () {311 const { lastLog } = this312 expect(lastLog.get('message')).to.eq('foo')313 })314 })315 it('snapshots immediately', () => {316 cy.getCookie('foo').then(function () {317 const { lastLog } = this318 expect(lastLog.get('snapshots').length).to.eq(1)319 expect(lastLog.get('snapshots')[0]).to.be.an('object')320 })321 })322 it('#consoleProps', () => {323 cy.getCookie('foo').then(function (cookie) {324 expect(cookie).to.deep.eq({ name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false })325 const c = this.lastLog.invoke('consoleProps')326 expect(c['Yielded']).to.deep.eq(cookie)327 })328 })329 it('#consoleProps when no cookie found', () => {330 cy.getCookie('bar').then(function (cookie) {331 expect(cookie).to.be.null332 const c = this.lastLog.invoke('consoleProps')333 expect(c['Yielded']).to.eq('null')334 expect(c['Note']).to.eq('No cookie with the name: \'bar\' was found.')335 })336 })337 })338 })339 context('#setCookie', () => {340 beforeEach(() => {341 cy.stub(Cypress.utils, 'addTwentyYears').returns(12345)342 })343 it('returns set cookie', () => {344 Cypress.automation.withArgs('set:cookie').resolves({345 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: false, httpOnly: false, expiry: 12345,346 })347 cy.setCookie('foo', 'bar').should('deep.eq', {348 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: false, httpOnly: false, expiry: 12345,349 })350 .then(() => {351 expect(Cypress.automation).to.be.calledWith(352 'set:cookie',353 { domain: 'localhost', name: 'foo', value: 'bar', path: '/', secure: false, httpOnly: false, expiry: 12345, sameSite: undefined },354 )355 })356 })357 it('can change options', () => {358 Cypress.automation.withArgs('set:cookie').resolves({359 name: 'foo', value: 'bar', domain: 'brian.dev.local', path: '/foo', secure: true, httpOnly: true, expiry: 987,360 })361 cy.setCookie('foo', 'bar', { domain: 'brian.dev.local', path: '/foo', secure: true, httpOnly: true, expiry: 987 }).should('deep.eq', {362 name: 'foo', value: 'bar', domain: 'brian.dev.local', path: '/foo', secure: true, httpOnly: true, expiry: 987,363 })364 .then(() => {365 expect(Cypress.automation).to.be.calledWith(366 'set:cookie',367 { domain: 'brian.dev.local', name: 'foo', value: 'bar', path: '/foo', secure: true, httpOnly: true, expiry: 987, sameSite: undefined },368 )369 })370 })371 it('does not mutate options', () => {372 Cypress.automation.resolves()373 const options = {}374 cy.setCookie('foo', 'bar', {}).then(() => {375 expect(options).deep.eq({})376 })377 })378 it('can set cookies with sameSite', () => {379 Cypress.automation.restore()380 Cypress.utils.addTwentyYears.restore()381 cy.setCookie('one', 'bar', { sameSite: 'none', secure: true })382 cy.getCookie('one').should('include', { sameSite: 'no_restriction' })383 cy.setCookie('two', 'bar', { sameSite: 'no_restriction', secure: true })384 cy.getCookie('two').should('include', { sameSite: 'no_restriction' })385 cy.setCookie('three', 'bar', { sameSite: 'Lax' })386 cy.getCookie('three').should('include', { sameSite: 'lax' })387 cy.setCookie('four', 'bar', { sameSite: 'Strict' })388 cy.getCookie('four').should('include', { sameSite: 'strict' })389 cy.setCookie('five', 'bar')390 // @see https://bugzilla.mozilla.org/show_bug.cgi?id=1624668391 if (Cypress.isBrowser('firefox')) {392 cy.getCookie('five').should('include', { sameSite: 'no_restriction' })393 } else {394 cy.getCookie('five').should('not.have.property', 'sameSite')395 }396 })397 describe('timeout', () => {398 it('sets timeout to Cypress.config(responseTimeout)', {399 responseTimeout: 2500,400 }, () => {401 Cypress.automation.resolves(null)402 const timeout = cy.spy(Promise.prototype, 'timeout')403 cy.setCookie('foo', 'bar').then(() => {404 expect(timeout).to.be.calledWith(2500)405 })406 })407 it('can override timeout', () => {408 Cypress.automation.resolves(null)409 const timeout = cy.spy(Promise.prototype, 'timeout')410 cy.setCookie('foo', 'bar', { timeout: 1000 }).then(() => {411 expect(timeout).to.be.calledWith(1000)412 })413 })414 it('clears the current timeout and restores after success', () => {415 Cypress.automation.resolves(null)416 cy.timeout(100)417 cy.spy(cy, 'clearTimeout')418 cy.setCookie('foo', 'bar').then(() => {419 expect(cy.clearTimeout).to.be.calledWith('set:cookie')420 // restores the timeout afterwards421 expect(cy.timeout()).to.eq(100)422 })423 })424 })425 describe('errors', {426 defaultCommandTimeout: 100,427 }, () => {428 beforeEach(function () {429 this.logs = []430 cy.on('log:added', (attrs, log) => {431 if (attrs.name === 'setCookie') {432 this.lastLog = log433 this.logs.push(log)434 }435 })436 return null437 })438 it('logs once on error', function (done) {439 const error = new Error('some err message')440 error.name = 'foo'441 Cypress.automation.rejects(error)442 cy.on('fail', (err) => {443 const { lastLog } = this444 expect(this.logs.length).to.eq(1)445 expect(lastLog.get('error').message).to.include('some err message')446 expect(lastLog.get('error').name).to.eq('CypressError')447 done()448 })449 cy.setCookie('foo', 'bar')450 })451 it('throws after timing out', function (done) {452 Cypress.automation.resolves(Promise.delay(1000))453 cy.on('fail', (err) => {454 const { lastLog } = this455 expect(this.logs.length).to.eq(1)456 expect(lastLog.get('error')).to.eq(err)457 expect(lastLog.get('state')).to.eq('failed')458 expect(lastLog.get('name')).to.eq('setCookie')459 expect(lastLog.get('message')).to.eq('foo, bar')460 expect(err.message).to.include('`cy.setCookie()` timed out waiting `50ms` to complete.')461 expect(err.docsUrl).to.eq('https://on.cypress.io/setcookie')462 done()463 })464 cy.setCookie('foo', 'bar', { timeout: 50 })465 })466 it('requires a string name', function (done) {467 cy.on('fail', (err) => {468 const { lastLog } = this469 expect(this.logs.length).to.eq(1)470 expect(lastLog.get('error').message).to.eq('`cy.setCookie()` must be passed two string arguments for `name` and `value`.')471 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/setcookie')472 expect(lastLog.get('error')).to.eq(err)473 done()474 })475 cy.setCookie(123)476 })477 it('requires a string value', function (done) {478 cy.on('fail', (err) => {479 const { lastLog } = this480 expect(this.logs.length).to.eq(1)481 expect(lastLog.get('error').message).to.eq('`cy.setCookie()` must be passed two string arguments for `name` and `value`.')482 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/setcookie')483 expect(lastLog.get('error')).to.eq(err)484 done()485 })486 cy.setCookie('foo', 123)487 })488 it('when an invalid samesite prop is supplied', function (done) {489 cy.on('fail', (err) => {490 const { lastLog } = this491 expect(this.logs.length).to.eq(1)492 expect(lastLog.get('error').message).to.eq(stripIndent`493 If a \`sameSite\` value is supplied to \`cy.setCookie()\`, it must be a string from the following list:494 > no_restriction, lax, strict495 You passed:496 > bad`)497 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/setcookie')498 expect(lastLog.get('error')).to.eq(err)499 done()500 })501 cy.setCookie('foo', 'bar', { sameSite: 'bad' })502 })503 it('when samesite=none is supplied and secure is not set', function (done) {504 cy.on('fail', (err) => {505 const { lastLog } = this506 expect(this.logs.length).to.eq(1)507 expect(lastLog.get('error').message).to.eq(stripIndent`508 Only cookies with the \`secure\` flag set to \`true\` can use \`sameSite: 'None'\`.509 Pass \`secure: true\` to \`cy.setCookie()\` to set a cookie with \`sameSite: 'None'\`.`)510 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/setcookie')511 expect(lastLog.get('error')).to.eq(err)512 done()513 })514 cy.setCookie('foo', 'bar', { sameSite: 'None' })515 })516 context('when setting an invalid cookie', () => {517 it('throws an error if the backend responds with an error', (done) => {518 const err = new Error('backend could not set cookie')519 Cypress.automation.withArgs('set:cookie').rejects(err)520 cy.on('fail', (err) => {521 expect(Cypress.automation.withArgs('set:cookie')).to.be.calledOnce522 expect(err.message).to.contain('unexpected error setting the requested cookie')523 expect(err.message).to.contain(err.message)524 done()525 })526 // browser backend should yell since this is invalid527 cy.setCookie('foo', ' bar')528 })529 })530 })531 describe('.log', () => {532 beforeEach(function () {533 cy.on('log:added', (attrs, log) => {534 if (attrs.name === 'setCookie') {535 this.lastLog = log536 }537 })538 Cypress.automation539 .withArgs('set:cookie', {540 domain: 'localhost', name: 'foo', value: 'bar', path: '/', secure: false, httpOnly: false, expiry: 12345, sameSite: undefined,541 })542 .resolves({543 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false,544 })545 })546 it('can turn off logging', () => {547 cy.setCookie('foo', 'bar', { log: false }).then(function () {548 expect(this.log).to.be.undefined549 })550 })551 it('ends immediately', () => {552 cy.setCookie('foo', 'bar').then(function () {553 const { lastLog } = this554 expect(lastLog.get('ended')).to.be.true555 expect(lastLog.get('state')).to.eq('passed')556 })557 })558 it('snapshots immediately', () => {559 cy.setCookie('foo', 'bar').then(function () {560 const { lastLog } = this561 expect(lastLog.get('snapshots').length).to.eq(1)562 expect(lastLog.get('snapshots')[0]).to.be.an('object')563 })564 })565 it('#consoleProps', () => {566 cy.setCookie('foo', 'bar').then(function (cookie) {567 expect(cookie).to.deep.eq({ name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false })568 const c = this.lastLog.invoke('consoleProps')569 expect(c['Yielded']).to.deep.eq(cookie)570 })571 })572 })573 })574 context('#clearCookie', () => {575 it('returns null', () => {576 Cypress.automation.withArgs('clear:cookie').resolves(null)577 cy.clearCookie('foo').should('be.null').then(() => {578 expect(Cypress.automation).to.be.calledWith(579 'clear:cookie',580 { domain: 'localhost', name: 'foo' },581 )582 })583 })584 describe('timeout', () => {585 it('sets timeout to Cypress.config(responseTimeout)', {586 responseTimeout: 2500,587 }, () => {588 Cypress.automation.resolves(null)589 const timeout = cy.spy(Promise.prototype, 'timeout')590 cy.clearCookie('foo').then(() => {591 expect(timeout).to.be.calledWith(2500)592 })593 })594 it('can override timeout', () => {595 Cypress.automation.resolves(null)596 const timeout = cy.spy(Promise.prototype, 'timeout')597 cy.clearCookie('foo', { timeout: 1000 }).then(() => {598 expect(timeout).to.be.calledWith(1000)599 })600 })601 it('clears the current timeout and restores after success', () => {602 Cypress.automation.resolves([])603 cy.timeout(100)604 cy.spy(cy, 'clearTimeout')605 cy.clearCookie('foo').then(() => {606 expect(cy.clearTimeout).to.be.calledWith('clear:cookie')607 // restores the timeout afterwards608 expect(cy.timeout()).to.eq(100)609 })610 })611 })612 describe('errors', {613 defaultCommandTimeout: 100,614 }, () => {615 beforeEach(function () {616 this.logs = []617 cy.on('log:added', (attrs, log) => {618 if (attrs.name === 'clearCookie') {619 this.lastLog = log620 this.logs.push(log)621 }622 })623 return null624 })625 it('logs once on error', function (done) {626 const error = new Error('some err message')627 error.name = 'foo'628 error.stack = 'stack'629 Cypress.automation.rejects(error)630 cy.on('fail', (err) => {631 const { lastLog } = this632 expect(this.logs.length).to.eq(1)633 expect(lastLog.get('error').message).to.contain(`\`cy.clearCookie()\` had an unexpected error clearing the requested cookie in ${Cypress.browser.displayName}.`)634 expect(lastLog.get('error').message).to.contain('some err message')635 done()636 })637 cy.clearCookie('foo')638 })639 it('throws after timing out', function (done) {640 Cypress.automation.resolves(Promise.delay(1000))641 cy.on('fail', (err) => {642 const { lastLog } = this643 expect(this.logs.length).to.eq(1)644 expect(lastLog.get('error')).to.eq(err)645 expect(lastLog.get('state')).to.eq('failed')646 expect(lastLog.get('name')).to.eq('clearCookie')647 expect(lastLog.get('message')).to.eq('foo')648 expect(err.message).to.eq('`cy.clearCookie()` timed out waiting `50ms` to complete.')649 expect(err.docsUrl).to.eq('https://on.cypress.io/clearcookie')650 done()651 })652 cy.clearCookie('foo', { timeout: 50 })653 })654 it('requires a string name', function (done) {655 cy.on('fail', (err) => {656 const { lastLog } = this657 expect(this.logs.length).to.eq(1)658 expect(lastLog.get('error').message).to.eq('`cy.clearCookie()` must be passed a string argument for name.')659 expect(lastLog.get('error').docsUrl).to.eq('https://on.cypress.io/clearcookie')660 expect(lastLog.get('error')).to.eq(err)661 done()662 })663 cy.clearCookie(123)664 })665 })666 describe('.log', () => {667 beforeEach(function () {668 cy.on('log:added', (attrs, log) => {669 if (attrs.name === 'clearCookie') {670 this.lastLog = log671 }672 })673 Cypress.automation674 .withArgs('clear:cookie', { domain: 'localhost', name: 'foo' })675 .resolves({676 name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false,677 })678 .withArgs('clear:cookie', { domain: 'localhost', name: 'bar' })679 .resolves(null)680 })681 it('can turn off logging', () => {682 cy.clearCookie('foo', { log: false }).then(function () {683 expect(this.log).to.be.undefined684 })685 })686 it('ends immediately', () => {687 cy.clearCookie('foo').then(function () {688 const { lastLog } = this689 expect(lastLog.get('ended')).to.be.true690 expect(lastLog.get('state')).to.eq('passed')691 })692 })693 it('snapshots immediately', () => {694 cy.clearCookie('foo').then(function () {695 const { lastLog } = this696 expect(lastLog.get('snapshots').length).to.eq(1)697 expect(lastLog.get('snapshots')[0]).to.be.an('object')698 })699 })700 it('#consoleProps', () => {701 cy.clearCookie('foo').then(function (cookie) {702 expect(cookie).to.be.null703 const c = this.lastLog.invoke('consoleProps')704 expect(c['Yielded']).to.eq('null')705 expect(c['Cleared Cookie']).to.deep.eq({ name: 'foo', value: 'bar', domain: 'localhost', path: '/', secure: true, httpOnly: false })706 })707 })708 it('#consoleProps when no matching cookie was found', () => {709 cy.clearCookie('bar').then(function (cookie) {710 expect(cookie).to.be.null711 const c = this.lastLog.invoke('consoleProps')712 expect(c['Yielded']).to.eq('null')713 expect(c['Cleared Cookie']).to.be.undefined714 expect(c['Note']).to.eq('No cookie with the name: \'bar\' was found or removed.')715 })716 })717 })718 })719 context('#clearCookies', () => {720 it('returns null', () => {721 Cypress.automation.withArgs('get:cookies').resolves([])722 cy.clearCookies().should('be.null')723 })724 it('does not call \'clear:cookies\' when no cookies were returned', () => {725 Cypress.automation.withArgs('get:cookies').resolves([])726 cy.clearCookies().then(() => {727 expect(Cypress.automation).not.to.be.calledWith(728 'clear:cookies',729 )730 })731 })732 it('calls \'clear:cookies\' only with clearableCookies', () => {733 Cypress.automation734 .withArgs('get:cookies')735 .resolves([736 { name: 'foo' },737 { name: 'bar' },738 ])739 .withArgs('clear:cookies', [740 { name: 'foo', domain: 'localhost' },741 ])742 .resolves({743 name: 'foo',744 })745 cy.stub(Cypress.Cookies, 'getClearableCookies')746 .withArgs([{ name: 'foo' }, { name: 'bar' }])747 .returns([{ name: 'foo' }])748 cy.clearCookies().should('be.null').then(() => {749 expect(Cypress.automation).to.be.calledWith(750 'clear:cookies',751 [{ name: 'foo', domain: 'localhost' }],752 )753 })754 })755 it('calls \'clear:cookies\' with all cookies', () => {756 Cypress.Cookies.preserveOnce('bar', 'baz')757 Cypress.automation758 .withArgs('get:cookies')759 .resolves([760 { name: 'foo' },761 { name: 'bar' },762 { name: 'baz' },763 ])764 .withArgs('clear:cookies', [765 { name: 'foo', domain: 'localhost' },766 ])767 .resolves({768 name: 'foo',769 })770 .withArgs('clear:cookies', [771 { name: 'foo', domain: 'localhost' },772 { name: 'bar', domain: 'localhost' },773 { name: 'baz', domain: 'localhost' },774 ])775 .resolves({776 name: 'foo',777 })778 cy779 .clearCookies().should('be.null').then(() => {780 expect(Cypress.automation).to.be.calledWith(781 'clear:cookies',782 [{ name: 'foo', domain: 'localhost' }],783 )784 }).clearCookies().should('be.null').then(() => {785 expect(Cypress.automation).to.be.calledWith(786 'clear:cookies', [787 { name: 'foo', domain: 'localhost' },788 { name: 'bar', domain: 'localhost' },789 { name: 'baz', domain: 'localhost' },790 ],791 )792 })793 })794 describe('timeout', () => {795 beforeEach(() => {796 Cypress.automation797 .withArgs('get:cookies')798 .resolves([{}])799 .withArgs('clear:cookies')800 .resolves({})801 })802 it('sets timeout to Cypress.config(responseTimeout)', {803 responseTimeout: 2500,804 }, () => {805 Cypress.automation.resolves([])806 const timeout = cy.spy(Promise.prototype, 'timeout')807 cy.clearCookies().then(() => {808 expect(timeout).to.be.calledWith(2500)809 })810 })811 it('can override timeout', () => {812 Cypress.automation.resolves([])813 const timeout = cy.spy(Promise.prototype, 'timeout')814 cy.clearCookies({ timeout: 1000 }).then(() => {815 expect(timeout).to.be.calledWith(1000)816 })817 })818 it('clears the current timeout and restores after success', () => {819 cy.timeout(100)820 cy.spy(cy, 'clearTimeout')821 cy.clearCookies().then(() => {822 expect(cy.clearTimeout).to.be.calledWith('get:cookies')823 expect(cy.clearTimeout).to.be.calledWith('clear:cookies')824 // restores the timeout afterwards825 expect(cy.timeout()).to.eq(100)826 })827 })828 })829 describe('errors', {830 defaultCommandTimeout: 100,831 }, () => {832 beforeEach(function () {833 this.logs = []834 cy.on('log:added', (attrs, log) => {835 if (attrs.name === 'clearCookies') {836 this.lastLog = log837 this.logs.push(log)838 }839 })840 return null841 })842 it('logs once on \'get:cookies\' error', function (done) {843 const error = new Error('some err message')844 error.name = 'foo'845 error.stack = 'some err message\n at fn (foo.js:1:1)'846 Cypress.automation.rejects(error)847 cy.on('fail', (err) => {848 const { lastLog } = this849 expect(this.logs.length).to.eq(1)850 expect(lastLog.get('error').message).to.contain(`\`cy.clearCookies()\` had an unexpected error clearing cookies in ${Cypress.browser.displayName}.`)851 expect(lastLog.get('error').message).to.contain('some err message')852 expect(lastLog.get('error')).to.eq(err)853 done()854 })855 cy.clearCookies()856 })857 it('throws after timing out', function (done) {858 Cypress.automation.resolves([{ name: 'foo' }])859 Cypress.automation.withArgs('clear:cookies').resolves(Promise.delay(1000))860 cy.on('fail', (err) => {861 const { lastLog } = this862 expect(this.logs.length).to.eq(1)863 expect(lastLog.get('error')).to.eq(err)864 expect(lastLog.get('state')).to.eq('failed')865 expect(lastLog.get('name')).to.eq('clearCookies')866 expect(lastLog.get('message')).to.eq('')867 expect(err.message).to.eq('`cy.clearCookies()` timed out waiting `50ms` to complete.')868 expect(err.docsUrl).to.eq('https://on.cypress.io/clearcookies')869 done()870 })871 cy.clearCookies({ timeout: 50 })872 })873 it('logs once on \'clear:cookies\' error', function (done) {874 Cypress.automation.withArgs('get:cookies').resolves([875 { name: 'foo' }, { name: 'bar' },876 ])877 const error = new Error('some err message')878 error.name = 'foo'879 error.stack = 'stack'880 Cypress.automation.withArgs('clear:cookies').rejects(error)881 cy.on('fail', (err) => {882 const { lastLog } = this883 expect(this.logs.length).to.eq(1)884 expect(lastLog.get('error').message).to.contain(`\`cy.clearCookies()\` had an unexpected error clearing cookies in ${Cypress.browser.displayName}.`)885 expect(lastLog.get('error').message).to.contain('some err message')886 expect(lastLog.get('error')).to.eq(err)887 done()888 })889 cy.clearCookies()890 })891 })892 describe('.log', () => {893 beforeEach(function () {894 cy.on('log:added', (attrs, log) => {895 if (attrs.name === 'clearCookies') {896 this.lastLog = log897 }898 })899 Cypress.automation900 .withArgs('get:cookies', { domain: 'localhost' })901 .resolves([{ name: 'foo' }])902 .withArgs('clear:cookies', [{ name: 'foo', domain: 'localhost' }])903 .resolves([904 { name: 'foo' },905 ])906 })907 it('can turn off logging', () => {908 cy.clearCookies({ log: false }).then(function () {909 expect(this.log).to.be.undefined910 })911 })912 it('ends immediately', () => {913 cy.clearCookies().then(function () {914 const { lastLog } = this915 expect(lastLog.get('ended')).to.be.true916 expect(lastLog.get('state')).to.eq('passed')917 })918 })919 it('snapshots immediately', () => {920 cy.clearCookies().then(function () {921 const { lastLog } = this922 expect(lastLog.get('snapshots').length).to.eq(1)923 expect(lastLog.get('snapshots')[0]).to.be.an('object')924 })925 })926 it('#consoleProps', () => {927 cy.clearCookies().then(function (cookies) {928 expect(cookies).to.be.null929 const c = this.lastLog.invoke('consoleProps')930 expect(c['Yielded']).to.eq('null')931 expect(c['Cleared Cookies']).to.deep.eq([{ name: 'foo' }])932 expect(c['Num Cookies']).to.eq(1)933 })934 })935 })936 describe('.log with no cookies returned', () => {937 beforeEach(function () {938 cy.on('log:added', (attrs, log) => {939 if (attrs.name === 'clearCookies') {940 this.lastLog = log941 }942 })943 Cypress.automation944 .withArgs('get:cookies', { domain: 'localhost' })945 .resolves([])946 })947 it('#consoleProps', () => {948 cy.clearCookies().then(function (cookies) {949 expect(cookies).to.be.null950 const c = this.lastLog.invoke('consoleProps')951 expect(c['Yielded']).to.eq('null')952 expect(c['Cleared Cookies']).to.be.undefined953 expect(c['Note']).to.eq('No cookies were found or removed.')954 })955 })956 })957 describe('.log when no cookies were cleared', () => {958 beforeEach(function () {959 cy.on('log:added', (attrs, log) => {960 if (attrs.name === 'clearCookies') {961 this.lastLog = log962 }963 })964 Cypress.automation965 .withArgs('get:cookies', { domain: 'localhost' })966 .resolves([{ name: 'foo' }])967 .withArgs('clear:cookies', [{ name: 'foo', domain: 'localhost' }])968 .resolves([])969 })970 it('#consoleProps', () => {971 cy.clearCookies().then(function (cookies) {972 expect(cookies).to.be.null973 const c = this.lastLog.invoke('consoleProps')974 expect(c['Yielded']).to.eq('null')975 expect(c['Cleared Cookies']).to.be.undefined976 expect(c['Note']).to.eq('No cookies were found or removed.')977 })978 })979 })980 })981 context('Cypress.cookies.defaults', () => {982 it('throws error on use of renamed whitelist option', (done) => {983 cy.on('fail', (err) => {984 expect(err.message).to.include('`Cypress.Cookies.defaults` `whitelist` option has been renamed to `preserve`. Please rename `whitelist` to `preserve`.')985 done()986 })987 Cypress.Cookies.defaults({988 whitelist: 'session_id',989 })990 })991 })...
screenshot_spec.js
Source:screenshot_spec.js
1const $ = require('jquery')2const { _, Promise, Screenshot } = Cypress3const getViewportHeight = () => {4 return Math.min(cy.state('viewportHeight'), $(cy.state('window')).height())5}6describe('src/cy/commands/screenshot', () => {7 beforeEach(function () {8 cy.stub(Cypress, 'automation').callThrough()9 this.serverResult = {10 path: '/path/to/screenshot',11 size: 12,12 dimensions: { width: 20, height: 20 },13 multipart: false,14 pixelRatio: 1,15 takenAt: new Date().toISOString(),16 name: 'name',17 blackout: ['.foo'],18 testAttemptIndex: 0,19 duration: 100,20 }21 this.screenshotConfig = {22 capture: 'viewport',23 screenshotOnRunFailure: true,24 disableTimersAndAnimations: true,25 scale: true,26 blackout: ['.foo'],27 }28 })29 context('runnable:after:run:async', () => {30 it('is noop when not isTextTerminal', () => {31 // backup this property so we set it back to whatever32 // is correct based on what mode we're currently in33 const isTextTerminal = Cypress.config('isTextTerminal')34 Cypress.config('isTextTerminal', false)35 cy.spy(Cypress, 'action').log(false)36 const test = {37 err: new Error,38 }39 const runnable = cy.state('runnable')40 Cypress.action('runner:runnable:after:run:async', test, runnable)41 .then(() => {42 expect(Cypress.action).not.to.be.calledWith('test:set:state')43 expect(Cypress.automation).not.to.be.called44 })45 .finally(() => {46 Cypress.config('isTextTerminal', isTextTerminal)47 })48 })49 it('is noop when no test.err', () => {50 Cypress.config('isInteractive', false)51 cy.spy(Cypress, 'action').log(false)52 const test = {}53 const runnable = cy.state('runnable')54 Cypress.action('runner:runnable:after:run:async', test, runnable)55 .then(() => {56 expect(Cypress.action).not.to.be.calledWith('test:set:state')57 expect(Cypress.automation).not.to.be.called58 })59 })60 it('is noop when screenshotOnRunFailure is false', () => {61 Cypress.config('isInteractive', false)62 cy.stub(Screenshot, 'getConfig').returns({63 screenshotOnRunFailure: false,64 })65 cy.spy(Cypress, 'action').log(false)66 const test = {67 err: new Error,68 }69 const runnable = cy.state('runnable')70 Cypress.action('runner:runnable:after:run:async', test, runnable)71 .then(() => {72 expect(Cypress.action).not.to.be.calledWith('test:set:state')73 expect(Cypress.automation).not.to.be.called74 })75 })76 it('is noop when screenshotOnRunFailure is false', () => {77 Cypress.config('isInteractive', false)78 Cypress.config('screenshotOnRunFailure', false)79 cy.spy(Cypress, 'action').log(false)80 const test = {81 err: new Error,82 }83 const runnable = cy.state('runnable')84 Cypress.action('runner:runnable:after:run:async', test, runnable)85 .then(() => {86 expect(Cypress.action).not.to.be.calledWith('cy:test:set:state')87 expect(Cypress.automation).not.to.be.called88 })89 })90 it('sends before/after events', function () {91 Cypress.config('isInteractive', false)92 this.screenshotConfig.scale = false93 cy.stub(Screenshot, 'getConfig').returns(this.screenshotConfig)94 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)95 cy.stub(Cypress, 'action').log(false)96 .callThrough()97 .withArgs('cy:before:screenshot')98 .yieldsAsync()99 const test = { id: '123', err: new Error() }100 const runnable = cy.state('runnable')101 Cypress.action('runner:runnable:after:run:async', test, runnable)102 .then(() => {103 expect(Cypress.action).to.be.calledWith('cy:before:screenshot', {104 id: runnable.id,105 isOpen: true,106 appOnly: false,107 scale: true,108 waitForCommandSynchronization: true,109 disableTimersAndAnimations: true,110 blackout: [],111 testAttemptIndex: 0,112 })113 expect(Cypress.action).to.be.calledWith('cy:after:screenshot', {114 id: runnable.id,115 isOpen: false,116 appOnly: false,117 scale: true,118 waitForCommandSynchronization: true,119 disableTimersAndAnimations: true,120 blackout: [],121 testAttemptIndex: 0,122 })123 })124 })125 it('takes screenshot when not isInteractive', function () {126 Cypress.config('isInteractive', false)127 Cypress.config('screenshotOnRunFailure', true)128 cy.stub(Screenshot, 'getConfig').returns(this.screenshotConfig)129 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)130 const test = {131 id: '123',132 err: new Error,133 }134 const runnable = cy.state('runnable')135 Cypress.action('runner:runnable:after:run:async', test, runnable)136 .then(() => {137 expect(Cypress.automation).to.be.calledWith('take:screenshot')138 let args = Cypress.automation.withArgs('take:screenshot').args[0][1]139 args = _.omit(args, 'padding', 'clip', 'userClip', 'viewport', 'takenPaths', 'startTime')140 expect(args).to.eql({141 testId: runnable.id,142 titles: [143 'src/cy/commands/screenshot',144 'runnable:after:run:async',145 runnable.title,146 ],147 capture: 'runner',148 simple: true,149 testFailure: true,150 blackout: [],151 scaled: true,152 testAttemptIndex: 0,153 })154 })155 })156 describe('if screenshot has been taken in test', () => {157 beforeEach(() => {158 cy.state('screenshotTaken', true)159 })160 it('sends simple: false', function () {161 Cypress.config('isInteractive', false)162 cy.stub(Screenshot, 'getConfig').returns(this.screenshotConfig)163 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)164 const test = {165 id: '123',166 err: new Error,167 }168 const runnable = cy.state('runnable')169 Cypress.action('runner:runnable:after:run:async', test, runnable)170 .delay(1) // before:screenshot promise requires a tick171 .then(() => {172 expect(Cypress.automation.withArgs('take:screenshot')).to.be.calledOnce173 let args = Cypress.automation.withArgs('take:screenshot').args[0][1]174 args = _.omit(args, 'padding', 'clip', 'userClip', 'viewport', 'takenPaths', 'startTime')175 expect(args).to.eql({176 testId: runnable.id,177 titles: [178 'src/cy/commands/screenshot',179 'runnable:after:run:async',180 'if screenshot has been taken in test',181 runnable.title,182 ],183 capture: 'runner',184 testFailure: true,185 simple: false,186 scaled: true,187 blackout: [],188 testAttemptIndex: 0,189 })190 })191 })192 })193 })194 context('runnable:after:run:async hooks', () => {195 beforeEach(function () {196 Cypress.config('isInteractive', false)197 cy.stub(Screenshot, 'getConfig').returns(this.screenshotConfig)198 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)199 const test = {200 id: '123',201 err: new Error,202 }203 const runnable = cy.state('runnable')204 Cypress.action('runner:runnable:after:run:async', test, runnable)205 .then(() => {206 expect(Cypress.automation).to.be.calledWith('take:screenshot')207 let args = Cypress.automation.withArgs('take:screenshot').args[0][1]208 args = _.omit(args, 'padding', 'clip', 'userClip', 'viewport', 'takenPaths', 'startTime')209 expect(args).to.eql({210 testId: runnable.id,211 titles: [212 'src/cy/commands/screenshot',213 'runnable:after:run:async hooks',214 'takes screenshot of hook title with test',215 '"before each" hook',216 ],217 capture: 'runner',218 simple: true,219 testFailure: true,220 scaled: true,221 blackout: [],222 testAttemptIndex: 0,223 })224 })225 })226 it('takes screenshot of hook title with test', () => {})227 })228 context('#screenshot', () => {229 beforeEach(function () {230 cy.stub(Screenshot, 'getConfig').returns(this.screenshotConfig)231 cy.stub(cy, 'pauseTimers').resolves()232 })233 it('sets name to undefined when not passed name', function () {234 const runnable = cy.state('runnable')235 runnable.title = 'foo bar'236 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)237 cy.screenshot().then(() => {238 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].name).to.be.undefined239 })240 })241 it('can pass name', function () {242 const runnable = cy.state('runnable')243 runnable.title = 'foo bar'244 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)245 cy.screenshot('my/file').then(() => {246 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].name).to.equal('my/file')247 })248 })249 it('calls onBeforeScreenshot callback with documentElement', function () {250 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)251 cy.stub(Screenshot, 'onBeforeScreenshot')252 cy.spy(Cypress, 'action').log(false)253 cy254 .screenshot('foo')255 .then(() => {256 expect(Screenshot.onBeforeScreenshot).to.be.calledOnce257 expect(Screenshot.onBeforeScreenshot.firstCall.args[0].get(0)).to.eq(cy.state('document').documentElement)258 })259 })260 it('calls onAfterScreenshot callback with documentElement', function () {261 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)262 cy.stub(Screenshot, 'onAfterScreenshot')263 cy.spy(Cypress, 'action').log(false)264 cy265 .screenshot('foo')266 .then(() => {267 expect(Screenshot.onAfterScreenshot).to.be.calledOnce268 expect(Screenshot.onAfterScreenshot.firstCall.args[0].get(0)).to.eq(cy.state('document').documentElement)269 })270 })271 it('pauses then unpauses timers if disableTimersAndAnimations is true', function () {272 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)273 cy.spy(Cypress, 'action').log(false)274 cy275 .screenshot('foo')276 .then(() => {277 expect(cy.pauseTimers).to.be.calledWith(true)278 expect(cy.pauseTimers).to.be.calledWith(false)279 })280 })281 it('does not pause timers if disableTimersAndAnimations is false', function () {282 this.screenshotConfig.disableTimersAndAnimations = false283 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)284 cy.spy(Cypress, 'action').log(false)285 cy286 .screenshot('foo')287 .then(() => {288 expect(cy.pauseTimers).not.to.be.called289 })290 })291 it('sends clip as userClip if specified', function () {292 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)293 cy.spy(Cypress, 'action').log(false)294 const clip = { width: 100, height: 100, x: 0, y: 0 }295 cy296 .screenshot({ clip })297 .then(() => {298 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].userClip).to.equal(clip)299 })300 })301 it('sends viewport dimensions of main browser window', function () {302 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)303 cy.spy(Cypress, 'action').log(false)304 cy305 .screenshot()306 .then(() => {307 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].viewport).to.eql({308 width: window.parent.innerWidth,309 height: window.parent.innerHeight,310 })311 })312 })313 it('can handle window w/length > 1 as a subject', () => {314 cy.visit('/fixtures/dom.html')315 cy.window().should('have.length.gt', 1)316 .screenshot()317 })318 describe('before/after events', () => {319 beforeEach(function () {320 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)321 cy.spy(Cypress, 'action').log(false)322 })323 it('sends before:screenshot', () => {324 const runnable = cy.state('runnable')325 cy326 .screenshot('foo')327 .then(() => {328 expect(Cypress.action.withArgs('cy:before:screenshot')).to.be.calledOnce329 expect(Cypress.action.withArgs('cy:before:screenshot').args[0][1]).to.eql({330 id: runnable.id,331 isOpen: true,332 appOnly: true,333 scale: true,334 waitForCommandSynchronization: false,335 disableTimersAndAnimations: true,336 blackout: ['.foo'],337 testAttemptIndex: 0,338 })339 })340 })341 it('sends after:screenshot', () => {342 const runnable = cy.state('runnable')343 cy344 .screenshot('foo')345 .then(() => {346 expect(Cypress.action.withArgs('cy:after:screenshot')).to.be.calledOnce347 expect(Cypress.action.withArgs('cy:after:screenshot').args[0][1]).to.eql({348 id: runnable.id,349 isOpen: false,350 appOnly: true,351 scale: true,352 waitForCommandSynchronization: false,353 disableTimersAndAnimations: true,354 blackout: ['.foo'],355 testAttemptIndex: 0,356 })357 })358 })359 it('always sends scale: true, waitForCommandSynchronization: true, and blackout: [] for non-app captures', function () {360 const runnable = cy.state('runnable')361 this.screenshotConfig.capture = 'runner'362 this.screenshotConfig.scale = false363 cy364 .screenshot('foo')365 .then(() => {366 expect(Cypress.action.withArgs('cy:before:screenshot').args[0][1]).to.eql({367 id: runnable.id,368 isOpen: true,369 appOnly: false,370 scale: true,371 waitForCommandSynchronization: true,372 disableTimersAndAnimations: true,373 blackout: [],374 testAttemptIndex: 0,375 })376 })377 })378 it('always sends waitForCommandSynchronization: false for viewport/fullPage captures', function () {379 const runnable = cy.state('runnable')380 this.screenshotConfig.waitForAnimations = true381 cy382 .screenshot('foo')383 .then(() => {384 expect(Cypress.action.withArgs('cy:before:screenshot').args[0][1]).to.eql({385 id: runnable.id,386 isOpen: true,387 appOnly: true,388 scale: true,389 waitForCommandSynchronization: false,390 disableTimersAndAnimations: true,391 blackout: ['.foo'],392 testAttemptIndex: 0,393 })394 })395 })396 })397 describe('capture: fullPage', () => {398 beforeEach(function () {399 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)400 cy.spy(Cypress, 'action').log(false)401 cy.viewport(600, 200)402 cy.visit('/fixtures/screenshots.html')403 })404 it('takes a screenshot for each time it needs to scroll', () => {405 cy.screenshot({ capture: 'fullPage' })406 .then(() => {407 expect(Cypress.automation.withArgs('take:screenshot')).to.be.calledThrice408 })409 })410 it('sends capture: fullPage', () => {411 cy.screenshot({ capture: 'fullPage' })412 .then(() => {413 const take = Cypress.automation.withArgs('take:screenshot')414 expect(take.args[0][1].capture).to.equal('fullPage')415 expect(take.args[1][1].capture).to.equal('fullPage')416 expect(take.args[2][1].capture).to.equal('fullPage')417 })418 })419 it('sends number of current screenshot for each time it needs to scroll', () => {420 cy.screenshot({ capture: 'fullPage' })421 .then(() => {422 const take = Cypress.automation.withArgs('take:screenshot')423 expect(take.args[0][1].current).to.equal(1)424 expect(take.args[1][1].current).to.equal(2)425 expect(take.args[2][1].current).to.equal(3)426 })427 })428 it('sends total number of screenshots for each time it needs to scroll', () => {429 cy.screenshot({ capture: 'fullPage' })430 .then(() => {431 const take = Cypress.automation.withArgs('take:screenshot')432 expect(take.args[0][1].total).to.equal(3)433 expect(take.args[1][1].total).to.equal(3)434 expect(take.args[2][1].total).to.equal(3)435 })436 })437 it('scrolls the window to the right place for each screenshot', () => {438 const win = cy.state('window')439 win.scrollTo(0, 100)440 const scrollTo = cy.spy(win, 'scrollTo')441 cy.screenshot({ capture: 'fullPage' })442 .then(() => {443 expect(scrollTo.getCall(0).args.join(',')).to.equal('0,0')444 expect(scrollTo.getCall(1).args.join(',')).to.equal('0,200')445 expect(scrollTo.getCall(2).args.join(',')).to.equal('0,400')446 })447 })448 it('scrolls the window back to the original place', () => {449 const win = cy.state('window')450 win.scrollTo(0, 100)451 const scrollTo = cy.spy(win, 'scrollTo')452 cy.screenshot({ capture: 'fullPage' })453 .then(() => {454 expect(scrollTo.getCall(3).args.join(',')).to.equal('0,100')455 })456 })457 it('sends the right clip values', () => {458 cy.screenshot({ capture: 'fullPage' })459 .then(() => {460 const take = Cypress.automation.withArgs('take:screenshot')461 expect(take.args[0][1].clip).to.eql({ x: 0, y: 0, width: 600, height: 200 })462 expect(take.args[1][1].clip).to.eql({ x: 0, y: 0, width: 600, height: 200 })463 expect(take.args[2][1].clip).to.eql({ x: 0, y: 120, width: 600, height: 80 })464 })465 })466 })467 describe('element capture', () => {468 beforeEach(function () {469 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)470 cy.spy(Cypress, 'action').log(false)471 cy.viewport(600, 200)472 cy.visit('/fixtures/screenshots.html')473 })474 it('yields an object with details', function () {475 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)476 cy.stub(Screenshot, 'onAfterScreenshot')477 cy.stub(Screenshot, 'onBeforeScreenshot')478 cy479 .get('.tall-element')480 .screenshot('name', {481 onBeforeScreenshot ($el) {482 expect($el).to.match('.tall-element')483 },484 onAfterScreenshot ($el, results) {485 expect($el).to.match('.tall-element')486 expect(results).to.deep.eq(this.serverResult)487 expect(results.name).to.eq('name')488 expect(results.blackout).to.eql(this.screenshotConfig.blackout)489 expect(results.dimensions).to.eql(this.serverResult.dimensions)490 expect(Screenshot.onBeforeScreenshot).to.be.calledOnce491 expect(Screenshot.onBeforeScreenshot.firstCall.args[0]).to.match('.tall-element')492 expect(Screenshot.onAfterScreenshot).not.to.be.called493 },494 })495 .then(() => {496 expect(Screenshot.onAfterScreenshot).to.be.calledOnce497 expect(Screenshot.onAfterScreenshot.firstCall.args[0]).to.match('.tall-element')498 })499 })500 it('takes a screenshot for each time it needs to scroll', () => {501 cy.get('.tall-element').screenshot()502 .then(() => {503 expect(Cypress.automation.withArgs('take:screenshot')).to.be.calledTwice504 })505 })506 it('sends number of current screenshot for each time it needs to scroll', () => {507 cy.get('.tall-element').screenshot()508 .then(() => {509 const take = Cypress.automation.withArgs('take:screenshot')510 expect(take.args[0][1].current).to.equal(1)511 expect(take.args[1][1].current).to.equal(2)512 })513 })514 it('sends total number of screenshots for each time it needs to scroll', () => {515 cy.get('.tall-element').screenshot()516 .then(() => {517 const take = Cypress.automation.withArgs('take:screenshot')518 expect(take.args[0][1].total).to.equal(2)519 expect(take.args[1][1].total).to.equal(2)520 })521 })522 it('scrolls the window to the right place for each screenshot', () => {523 const win = cy.state('window')524 win.scrollTo(0, 100)525 const scrollTo = cy.spy(win, 'scrollTo')526 cy.get('.tall-element').screenshot()527 .then(() => {528 expect(scrollTo.getCall(0).args.join(',')).to.equal('0,140')529 expect(scrollTo.getCall(1).args.join(',')).to.equal('0,340')530 })531 })532 it('scrolls the window back to the original place', () => {533 const win = cy.state('window')534 win.scrollTo(0, 100)535 const scrollTo = cy.spy(win, 'scrollTo')536 cy.get('.tall-element').screenshot()537 .then(() => {538 expect(scrollTo.getCall(2).args.join(',')).to.equal('0,100')539 })540 })541 it('sends the right clip values for elements that need scrolling', () => {542 const scrollTo = cy.spy(cy.state('window'), 'scrollTo')543 cy.get('.tall-element').screenshot()544 .then(() => {545 expect(scrollTo.getCall(0).args).to.eql([0, 140])546 const take = Cypress.automation.withArgs('take:screenshot')547 expect(take.args[0][1].clip).to.eql({ x: 20, y: 0, width: 560, height: 200 })548 expect(take.args[1][1].clip).to.eql({ x: 20, y: 60, width: 560, height: 120 })549 })550 })551 it('sends the right clip values for elements that don\'t need scrolling', () => {552 const scrollTo = cy.spy(cy.state('window'), 'scrollTo')553 cy.get('.short-element').screenshot()554 .then(() => {555 // even though we don't need to scroll, the implementation behaviour is to556 // try to scroll until the element is at the top of the viewport.557 expect(scrollTo.getCall(0).args).to.eql([0, 20])558 const take = Cypress.automation.withArgs('take:screenshot')559 expect(take.args[0][1].clip).to.eql({ x: 40, y: 0, width: 200, height: 100 })560 })561 })562 it('applies padding to clip values for elements that need scrolling', () => {563 const padding = 10564 const scrollTo = cy.spy(cy.state('window'), 'scrollTo')565 cy.get('.tall-element').screenshot({ padding })566 .then(() => {567 const viewportHeight = getViewportHeight()568 expect(scrollTo.getCall(0).args).to.eql([0, 140 - padding])569 expect(scrollTo.getCall(1).args).to.eql([0, (140 + viewportHeight) - padding])570 const take = Cypress.automation.withArgs('take:screenshot')571 expect(take.args[0][1].clip).to.eql({572 x: 20 - padding,573 y: 0,574 width: 560 + (padding * 2),575 height: viewportHeight,576 })577 expect(take.args[1][1].clip).to.eql({578 x: 20 - padding,579 y: 60 - padding,580 width: 560 + (padding * 2),581 height: 120 + (padding * 2),582 })583 })584 })585 it('applies padding to clip values for elements that don\'t need scrolling', () => {586 const padding = 10587 const scrollTo = cy.spy(cy.state('window'), 'scrollTo')588 cy.get('.short-element').screenshot({ padding })589 .then(() => {590 expect(scrollTo.getCall(0).args).to.eql([0, padding])591 const take = Cypress.automation.withArgs('take:screenshot')592 expect(take.args[0][1].clip).to.eql({593 x: 30,594 y: 0,595 width: 220,596 height: 120,597 })598 })599 })600 it('works with cy.within()', () => {601 cy.get('.short-element').within(() => {602 cy.screenshot()603 }).then(() => {604 const take = Cypress.automation.withArgs('take:screenshot')605 expect(take.args[0][1].clip).to.eql({ x: 40, y: 0, width: 200, height: 100 })606 })607 })608 // https://github.com/cypress-io/cypress/issues/14253609 it('ignores within subject when capturing the runner', () => {610 cy.get('.short-element').within(() => {611 cy.screenshot({ capture: 'runner' })612 }).then(() => {613 // the runner was captured614 expect(Cypress.action.withArgs('cy:before:screenshot').args[0][1].appOnly).to.be.true615 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].capture).to.equal('viewport')616 })617 })618 it('coerces capture option into \'app\'', function () {619 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)620 cy.get('.short-element').screenshot({ capture: 'runner' })621 .then(() => {622 expect(Cypress.action.withArgs('cy:before:screenshot').args[0][1].appOnly).to.be.true623 expect(Cypress.automation.withArgs('take:screenshot').args[0][1].capture).to.equal('viewport')624 })625 })626 it('passes through the existing $l subject', () => {627 cy628 .get('.short-element').then(($el) => {629 cy630 .get('.short-element')631 .screenshot()632 .then(($el2) => {633 expect($el2.get(0)).to.equal($el.get(0))634 })635 })636 })637 it('passes through window', () => {638 cy639 .window()640 .then((win) => {641 cy.wrap(win)642 .screenshot()643 .then((w) => {644 expect(win === w).to.be.true645 })646 })647 })648 it('passes through document', () => {649 cy650 .document()651 .then((doc) => {652 cy.wrap(doc)653 .screenshot()654 .then((d) => {655 expect(doc === d).to.be.true656 })657 })658 })659 // https://github.com/cypress-io/cypress/issues/6099660 it('can screenshot when element height changes on scroll', () => {661 cy.visit('fixtures/issue-6099.html')662 cy.get('main').screenshot()663 })664 })665 describe('timeout', () => {666 beforeEach(function () {667 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)668 })669 it('sets timeout to Cypress.config(responseTimeout)', {670 responseTimeout: 2500,671 }, () => {672 const timeout = cy.spy(Promise.prototype, 'timeout')673 cy.screenshot().then(() => {674 expect(timeout).to.be.calledWith(2500)675 })676 })677 it('can override timeout', () => {678 const timeout = cy.spy(Promise.prototype, 'timeout')679 cy.screenshot({ timeout: 1000 }).then(() => {680 expect(timeout).to.be.calledWith(1000)681 })682 })683 it('can override timeout and pass name', () => {684 const timeout = cy.spy(Promise.prototype, 'timeout')685 cy.screenshot('foo', { timeout: 1000 }).then(() => {686 expect(timeout).to.be.calledWith(1000)687 })688 })689 it('clears the current timeout and restores after success', () => {690 cy.timeout(100)691 cy.spy(cy, 'clearTimeout')692 cy.screenshot().then(() => {693 expect(cy.clearTimeout).to.be.calledWith('take:screenshot')694 // restores the timeout afterwards695 expect(cy.timeout()).to.eq(100)696 })697 })698 })699 describe('errors', {700 defaultCommandTimeout: 100,701 }, () => {702 beforeEach(function () {703 this.logs = []704 cy.on('log:added', (attrs, log) => {705 if (attrs.name === 'screenshot') {706 this.lastLog = log707 this.logs.push(log)708 }709 })710 this.assertErrorMessage = function (message, done) {711 cy.on('fail', (err) => {712 const lastErr = this.lastLog.get('error')713 expect(lastErr.message).to.eq(message)714 done()715 })716 }717 return null718 })719 it('throws if capture is not a string', function (done) {720 cy.on('fail', (err) => {721 const lastErr = this.lastLog.get('error')722 expect(lastErr.message).to.eq('`cy.screenshot()` `capture` option must be one of the following: `fullPage`, `viewport`, or `runner`. You passed: `true`')723 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')724 done()725 })726 cy.screenshot({ capture: true })727 })728 it('throws if capture is not a valid option', function (done) {729 cy.on('fail', (err) => {730 const lastErr = this.lastLog.get('error')731 expect(lastErr.message).to.eq('`cy.screenshot()` `capture` option must be one of the following: `fullPage`, `viewport`, or `runner`. You passed: `foo`')732 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')733 done()734 })735 cy.screenshot({ capture: 'foo' })736 })737 it('throws if scale is not a boolean', function (done) {738 cy.on('fail', (err) => {739 const lastErr = this.lastLog.get('error')740 expect(lastErr.message).to.eq('`cy.screenshot()` `scale` option must be a boolean. You passed: `foo`')741 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')742 done()743 })744 cy.screenshot({ scale: 'foo' })745 })746 it('throws if disableTimersAndAnimations is not a boolean', function (done) {747 cy.on('fail', (err) => {748 const lastErr = this.lastLog.get('error')749 expect(lastErr.message).to.eq('`cy.screenshot()` `disableTimersAndAnimations` option must be a boolean. You passed: `foo`')750 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')751 done()752 })753 cy.screenshot({ disableTimersAndAnimations: 'foo' })754 })755 it('throws if blackout is not an array', function (done) {756 cy.on('fail', (err) => {757 const lastErr = this.lastLog.get('error')758 expect(lastErr.message).to.eq('`cy.screenshot()` `blackout` option must be an array of strings. You passed: `foo`')759 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')760 done()761 })762 cy.screenshot({ blackout: 'foo' })763 })764 it('throws if blackout is not an array of strings', function (done) {765 cy.on('fail', (err) => {766 const lastErr = this.lastLog.get('error')767 expect(lastErr.message).to.eq('`cy.screenshot()` `blackout` option must be an array of strings. You passed: `true`')768 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')769 done()770 })771 cy.screenshot({ blackout: [true] })772 })773 it('throws if there is a 0px tall element height', function (done) {774 this.assertErrorMessage('`cy.screenshot()` only works with a screenshot area with a height greater than zero.', done)775 cy.visit('/fixtures/screenshots.html')776 cy.get('.empty-element').screenshot()777 })778 it('throws if padding is not a number', function (done) {779 this.assertErrorMessage('`cy.screenshot()` `padding` option must be either a number or an array of numbers with a maximum length of 4. You passed: `50px`', done)780 cy.screenshot({ padding: '50px' })781 })782 it('throws if padding is not an array of numbers', function (done) {783 this.assertErrorMessage('`cy.screenshot()` `padding` option must be either a number or an array of numbers with a maximum length of 4. You passed: `bad, bad, bad, bad`', done)784 cy.screenshot({ padding: ['bad', 'bad', 'bad', 'bad'] })785 })786 it('throws if padding is not an array with a length between 1 and 4', function (done) {787 this.assertErrorMessage('`cy.screenshot()` `padding` option must be either a number or an array of numbers with a maximum length of 4. You passed: `20, 10, 20, 10, 50`', done)788 cy.screenshot({ padding: [20, 10, 20, 10, 50] })789 })790 it('throws if padding is a large negative number that causes a 0px tall element height', function (done) {791 this.assertErrorMessage('`cy.screenshot()` only works with a screenshot area with a height greater than zero.', done)792 cy.visit('/fixtures/screenshots.html')793 cy.get('.tall-element').screenshot({ padding: -161 })794 })795 it('throws if clip is not an object', function (done) {796 this.assertErrorMessage('`cy.screenshot()` `clip` option must be an object with the keys `{ width, height, x, y }` and number values. You passed: `true`', done)797 cy.screenshot({ clip: true })798 })799 it('throws if clip is lacking proper keys', function (done) {800 this.assertErrorMessage('`cy.screenshot()` `clip` option must be an object with the keys `{ width, height, x, y }` and number values. You passed: `{x: 5}`', done)801 cy.screenshot({ clip: { x: 5 } })802 })803 it('throws if clip has extraneous keys', function (done) {804 this.assertErrorMessage('`cy.screenshot()` `clip` option must be an object with the keys `{ width, height, x, y }` and number values. You passed: `Object{5}`', done)805 cy.screenshot({ clip: { width: 100, height: 100, x: 5, y: 5, foo: 10 } })806 })807 it('throws if clip has non-number values', function (done) {808 this.assertErrorMessage('`cy.screenshot()` `clip` option must be an object with the keys `{ width, height, x, y }` and number values. You passed: `Object{4}`', done)809 cy.screenshot({ clip: { width: 100, height: 100, x: 5, y: '5' } })810 })811 it('throws if element capture with multiple elements', function (done) {812 cy.on('fail', (err) => {813 const lastErr = this.lastLog.get('error')814 expect(lastErr.message).to.eq('`cy.screenshot()` only works for a single element. You attempted to screenshot 4 elements.')815 expect(lastErr.docsUrl).to.eq('https://on.cypress.io/screenshot')816 done()817 })818 cy.visit('/fixtures/screenshots.html')819 cy.get('.multiple').screenshot()820 })821 it('logs once on error', function (done) {822 const error = new Error('some error')823 error.name = 'foo'824 error.stack = 'stack'825 Cypress.automation.withArgs('take:screenshot').rejects(error)826 cy.on('fail', (err) => {827 const { lastLog } = this828 expect(this.logs.length).to.eq(1)829 expect(lastLog.get('error').message).to.eq(error.message)830 expect(lastLog.get('error').name).to.eq(error.name)831 expect(lastLog.get('error').stack).to.eq(error.stack)832 expect(lastLog.get('error')).to.eq(err)833 done()834 })835 cy.screenshot()836 })837 it('throws after timing out', function (done) {838 Cypress.automation.withArgs('take:screenshot').resolves(Promise.delay(1000))839 cy.on('fail', (err) => {840 const { lastLog } = this841 expect(this.logs.length).to.eq(1)842 expect(lastLog.get('error')).to.eq(err)843 expect(lastLog.get('state')).to.eq('failed')844 expect(lastLog.get('name')).to.eq('screenshot')845 expect(lastLog.get('message')).to.eq('foo')846 expect(err.message).to.eq('`cy.screenshot()` timed out waiting `50ms` to complete.')847 expect(err.docsUrl).to.eq('https://on.cypress.io/screenshot')848 done()849 })850 cy.screenshot('foo', { timeout: 50 })851 })852 })853 describe('.log', () => {854 beforeEach(function () {855 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)856 cy.on('log:added', (attrs, log) => {857 if (attrs.name === 'screenshot') {858 this.lastLog = log859 }860 })861 return null862 })863 it('can turn off logging', () => {864 cy.screenshot('bar', { log: false }).then(function () {865 expect(this.lastLog).to.be.undefined866 })867 })868 it('ends immediately', () => {869 cy.screenshot().then(function () {870 const { lastLog } = this871 expect(lastLog.get('ended')).to.be.true872 expect(lastLog.get('state')).to.eq('passed')873 })874 })875 it('snapshots immediately', () => {876 cy.screenshot().then(function () {877 const { lastLog } = this878 expect(lastLog.get('snapshots').length).to.eq(1)879 expect(lastLog.get('snapshots')[0]).to.be.an('object')880 })881 })882 it('#consoleProps', function () {883 Cypress.automation.withArgs('take:screenshot').resolves(this.serverResult)884 let expected = _.extend({}, this.serverResult, this.screenshotConfig, {885 Command: 'screenshot',886 scaled: true,887 duration: '100ms',888 })889 expected = _.omit(expected, 'blackout', 'dimensions', 'screenshotOnRunFailure', 'scale', 'size')890 cy.screenshot().then(() => {891 const consoleProps = this.lastLog.invoke('consoleProps')892 const actual = _.omit(consoleProps, 'blackout', 'dimensions', 'size')893 const { width, height } = this.serverResult.dimensions894 expect(actual).to.eql(expected)895 expect(consoleProps.size).to.eq('12 B')896 expect(consoleProps.blackout).to.eql(this.screenshotConfig.blackout)897 expect(consoleProps.dimensions).to.equal(`${width}px x ${height}px`)898 })899 })900 })901 })...
offline_spec.js
Source:offline_spec.js
1// https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/server-communication__offline/cypress/integration/offline-spec.js2const goOffline = () => {3 cy.log('**go offline**')4 .then(() => {5 return Cypress.automation('remote:debugger:protocol', {6 command: 'Network.enable',7 });8 })9 .then(() => {10 return Cypress.automation('remote:debugger:protocol', {11 command: 'Network.emulateNetworkConditions',12 params: {13 offline: true,14 latency: -1,15 downloadThroughput: -1,16 uploadThroughput: -1,17 },18 });19 });20};21const goOnline = () => {22 // disable offline mode, otherwise we will break our tests :)23 cy.log('**go online**')24 .then(() => {25 // https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-emulateNetworkConditions26 return Cypress.automation('remote:debugger:protocol', {27 command: 'Network.emulateNetworkConditions',28 params: {29 offline: false,30 latency: -1,31 downloadThroughput: -1,32 uploadThroughput: -1,33 },34 });35 })36 .then(() => {37 return Cypress.automation('remote:debugger:protocol', {38 command: 'Network.disable',39 });40 });41};42describe('offline', () => {43 describe('site', { browser: '!firefox' }, () => {44 // make sure we get back online, even if a test fails45 // otherwise the Cypress can lose the browser connection46 beforeEach(goOnline);47 afterEach(goOnline);48 it('shows /migrate/ page', () => {49 const url = '/migrate/';50 const text = 'Migrate';51 cy.visit(url);...
network-status_spec.js
Source:network-status_spec.js
...5};6const assertOffline = () => {7 return cy.wrap(window).its('navigator.onLine').should('be.false');8};9Cypress.automation('remote:debugger:protocol', {10 command: 'Network.enable',11});12const goOffline = () => {13 cy.log('**offline**')14 .then(() => {15 return Cypress.automation('remote:debugger:protocol', {16 command: 'Network.emulateNetworkConditions',17 params: {18 type: false,19 offline: true,20 latency: -1,21 downloadThroughput: -1,22 uploadThroughput: -1,23 },24 });25 })26 .wait(2000);27};28const goOnline = () => {29 // disable offline mode, otherwise we will break our tests :)30 cy.log('**online**')31 .then(() => {32 // https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-emulateNetworkConditions33 return Cypress.automation('remote:debugger:protocol', {34 command: 'Network.emulateNetworkConditions',35 params: {36 type: true,37 offline: false,38 latency: -1,39 downloadThroughput: -1,40 uploadThroughput: -1,41 },42 });43 })44 .wait(2000);45};46const visit = (darkAppearance) => {47 goOnline();...
offline_mode_spec.js
Source:offline_mode_spec.js
1const goOnline = () => {2 cy.log('**go online**')3 .then(() => {4 return Cypress.automation('remote:debugger:protocol', {5 command: 'Network.emulateNetworkConditions',6 params: {7 offline: false,8 latency: -1,9 downloadThroughput: -1,10 uploadThroughput: -1,11 },12 });13 })14 .then(() => {15 return Cypress.automation('remote:debugger:protocol', {16 command: 'Network.disable',17 });18 });19};20const goOffline = () => {21 cy.log('**go offline**')22 .then(() => {23 return Cypress.automation('remote:debugger:protocol', {24 command: 'Network.enable',25 });26 })27 .then(() => {28 return Cypress.automation('remote:debugger:protocol', {29 command: 'Network.emulateNetworkConditions',30 params: {31 offline: true,32 latency: -1,33 downloadThroughput: -1,34 uploadThroughput: -1,35 },36 });37 });38};39describe('offline mode', { browser: '!firefox' }, () => {40 beforeEach(goOnline);41 afterEach(goOnline);42 it('shows progress bar when selecting a post', () => {...
Using AI Code Generation
1Cypress.Commands.add('automation', (command, ...args) => {2 return cy.window({ log: false }).then(win => {3 return win.Cypress.automation(command, ...args)4 })5})6Cypress.Commands.add('automation', (command, ...args) => {7 return cy.window({ log: false }).then(win => {8 return win.Cypress.automation(command, ...args)9 })10})11Cypress.Commands.add('automation', (command, ...args) => {12 return cy.window({ log: false }).then(win => {13 return win.Cypress.automation(command, ...args)14 })15})16Cypress.Commands.add('automation', (command, ...args) => {17 return cy.window({ log: false }).then(win => {18 return win.Cypress.automation(command, ...args)19 })20})21Cypress.Commands.add('automation', (command, ...args) => {22 return cy.window({ log: false }).then(win => {23 return win.Cypress.automation(command, ...args)24 })25})26Cypress.Commands.add('automation', (command, ...args) => {27 return cy.window({ log: false }).then(win => {28 return win.Cypress.automation(command, ...args)29 })30})31Cypress.Commands.add('automation', (command, ...args) => {32 return cy.window({ log: false }).then(win => {33 return win.Cypress.automation(command, ...args)34 })35})36Cypress.Commands.add('automation', (command, ...args) => {37 return cy.window({ log: false }).then(win => {38 return win.Cypress.automation(command, ...args)39 })40})41Cypress.Commands.add('automation', (command, ...args) => {42 return cy.window({ log: false }).then(win => {43 return win.Cypress.automation(command, ...args)44 })45})46Cypress.Commands.add('automation', (command, ...args)
Using AI Code Generation
1Cypress.Commands.add('getCookies', () => {2 .window()3 .then((win) => {4 return win.Cypress.automation('get:cookies', {log: false});5 });6});7import './commands';8Cypress.Commands.add('getCookies', () => {9 .window()10 .then((win) => {11 return win.Cypress.automation('get:cookies', {log: false});12 });13});14Cypress.Commands.add('getCookies', () => {15 .window()16 .then((win) => {17 return win.Cypress.automation('get:cookies', {log: false});18 });19});20import './commands';21Cypress.Commands.add('getCookies', () => {22 .window()23 .then((win) => {24 return win.Cypress.automation('get:cookies', {log: false});25 });26});27import './commands';28Cypress.Commands.add('getCookies', () => {29 .window()30 .then((win) => {31 return win.Cypress.automation('get:cookies', {log: false});32 });33});34import './commands';35Cypress.Commands.add('getCookies', () => {36 .window()37 .then((win) => {38 return win.Cypress.automation('get:cookies', {log: false});39 });40});41Cypress.Commands.add('getCookies', () => {42 .window()43 .then((win) => {44 return win.Cypress.automation('get:cookies', {log: false});45 });46});47Cypress.Commands.add('getCookies', () => {48 .window()49 .then((win) => {50 return win.Cypress.automation('get:cookies', {log: false});51 });52});53Cypress.Commands.add('getCookies', () => {54 .window()55 .then((win) => {56 return win.Cypress.automation('get:cookies', {log: false});57 });58});59Cypress.Commands.add('getCookies', () => {
Using AI Code Generation
1describe('My First Test', function() {2 it('Gets, types and asserts', function() {3 cy.get('#username').type('admin')4 cy.get('#password').type('admin')5 cy.get('#login-button').click()6 cy.wait(5000)7 cy.getCookies().then((cookies) => {8 cy.writeFile('cypress/fixtures/cookies.json', cookies)9 })10 })11})
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('#lst-ib').type('hello world')4 cy.get('.lsb').click()5 cy.get('.r').first().click()6 cy.get('.gsfi').should('have.value', 'hello world')7 })8})
Using AI Code Generation
1Cypress.Commands.add('setCookieValueFromAnotherCookie', (cookieName) => {2 cy.getCookie(cookieName).then((cookie) => {3 cy.log(`Cookie value is: ${cookie.value}`);4 cy.setCookie(cookieName, cookie.value);5 });6});7Cypress.Commands.add('setCookieValueFromAnotherCookie', (cookieName) => {8 cy.getCookie(cookieName).then((cookie) => {9 cy.log(`Cookie value is: ${cookie.value}`);10 cy.setCookie(cookieName, cookie.value);11 });12});13Cypress.Commands.add('setCookieValueFromAnotherCookie', (cookieName) => {14 cy.getCookie(cookieName).then((cookie) => {15 cy.log(`Cookie value is: ${cookie.value}`);16 cy.setCookie(cookieName, cookie.value);17 });18});19Cypress.Commands.add('setCookieValueFromAnotherCookie', (cookieName) => {20 cy.getCookie(cookieName).then((cookie) => {21 cy.log(`Cookie value is: ${cookie.value}`);22 cy.setCookie(cookieName, cookie.value);23 });24});25Cypress.Commands.add('setCookieValueFromAnotherCookie', (cookieName) => {26 cy.getCookie(cookieName).then((
Using AI Code Generation
1import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";2let cookie = null;3Given("I am logged in", () => {4 cy.get("#username").type("testuser");5 cy.get("#password").type("testpassword");6 cy.get("#login").click();7 cy.getCookie("token").then((c) => {8 cookie = c.value;9 });10});11When("I visit the home page", () => {12});13Then("I should see the data", () => {14 cy.request({15 headers: {16 Authorization: `Bearer ${cookie}`,17 },18 }).then((response) => {19 expect(response.body).to.have.property("data");20 });21});
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!!