How to use onAfterScreenshot method in Cypress

Best JavaScript code snippet using cypress

screenshot_spec.js

Source:screenshot_spec.js Github

copy

Full Screen

...16 expect(() => {17 Screenshot.onBeforeScreenshot()18 }).not.to.throw()19 expect(() => {20 Screenshot.onAfterScreenshot()21 }).not.to.throw()22 })23 context('.getConfig', () => {24 it('returns copy of config', () => {25 const config = Screenshot.getConfig()26 config.blackout.push('.foo')27 expect(Screenshot.getConfig().blackout).to.deep.eq(DEFAULTS.blackout)28 })29 })30 context('.defaults', () => {31 it('is noop if not called with any valid properties', () => {32 Screenshot.defaults({})33 expect(Screenshot.getConfig()).to.deep.eq(DEFAULTS)34 expect(() => {35 Screenshot.onBeforeScreenshot()36 }).not.to.throw()37 expect(() => {38 Screenshot.onAfterScreenshot()39 }).not.to.throw()40 })41 it('sets capture if specified', () => {42 Screenshot.defaults({43 capture: 'runner',44 })45 expect(Screenshot.getConfig().capture).to.eql('runner')46 })47 it('sets scale if specified', () => {48 Screenshot.defaults({49 scale: true,50 })51 expect(Screenshot.getConfig().scale).to.equal(true)52 })53 it('sets disableTimersAndAnimations if specified', () => {54 Screenshot.defaults({55 disableTimersAndAnimations: false,56 })57 expect(Screenshot.getConfig().disableTimersAndAnimations).to.equal(false)58 })59 it('sets screenshotOnRunFailure if specified', () => {60 Screenshot.defaults({61 screenshotOnRunFailure: false,62 })63 expect(Screenshot.getConfig().screenshotOnRunFailure).to.equal(false)64 })65 it('sets clip if specified', () => {66 Screenshot.defaults({67 clip: { width: 200, height: 100, x: 0, y: 0 },68 })69 expect(70 Screenshot.getConfig().clip,71 ).to.eql(72 { width: 200, height: 100, x: 0, y: 0 },73 )74 })75 it('sets and normalizes padding if specified', () => {76 const tests = [77 [50, [50, 50, 50, 50]],78 [[15], [15, 15, 15, 15]],79 [[30, 20], [30, 20, 30, 20]],80 [[10, 20, 30], [10, 20, 30, 20]],81 [[20, 10, 20, 10], [20, 10, 20, 10]],82 ]83 for (let test of tests) {84 const [input, expected] = test85 Screenshot.defaults({86 padding: input,87 })88 expect(Screenshot.getConfig().padding).to.eql(expected)89 }90 })91 it('sets onBeforeScreenshot if specified', () => {92 const onBeforeScreenshot = cy.stub()93 Screenshot.defaults({ onBeforeScreenshot })94 Screenshot.onBeforeScreenshot()95 expect(onBeforeScreenshot).to.be.called96 })97 it('sets onAfterScreenshot if specified', () => {98 const onAfterScreenshot = cy.stub()99 Screenshot.defaults({ onAfterScreenshot })100 Screenshot.onAfterScreenshot()101 expect(onAfterScreenshot).to.be.called102 })103 describe('errors', () => {104 it('throws if not passed an object', () => {105 const fn = () => {106 Screenshot.defaults()107 }108 expect(fn).to.throw()109 .with.property('message')110 .and.include('`Cypress.Screenshot.defaults()` must be called with an object. You passed: ``')111 expect(fn).to.throw()112 .with.property('docsUrl')113 .and.include('https://on.cypress.io/screenshot-api')114 })...

Full Screen

Full Screen

retries.mochaEvents.spec.js

Source:retries.mochaEvents.spec.js Github

copy

Full Screen

1const helpers = require('../support/helpers')2const { shouldHaveTestResults, getRunState, cleanseRunStateMap } = helpers3const { runIsolatedCypress, snapshotMochaEvents, getAutCypress } = helpers.createCypress({ config: { retries: 2, isTextTerminal: true, firefoxGcInterval: null } })4const { sinon } = Cypress5const match = Cypress.sinon.match6const threeTestsWithRetry = {7 suites: {8 'suite 1': {9 hooks: ['before', 'beforeEach', 'afterEach', 'after'],10 tests: [11 'test 1',12 { name: 'test 2', fail: 2 },13 'test 3',14 ],15 },16 },17}18describe('src/cypress/runner retries mochaEvents', { retries: 0 }, () => {19 // NOTE: for test-retries20 it('can set retry config', () => {21 runIsolatedCypress({}, { config: { retries: 1 } })22 .then(({ autCypress }) => {23 expect(autCypress.config()).to.has.property('retries', 1)24 })25 })26 it('simple retry', () => {27 runIsolatedCypress({28 suites: {29 'suite 1': {30 tests: [31 { name: 'test 1',32 fail: 1,33 },34 ],35 },36 },37 }, { config: { retries: 1 } })38 .then(snapshotMochaEvents)39 })40 it('test retry with hooks', () => {41 runIsolatedCypress({42 suites: {43 'suite 1': {44 hooks: ['before', 'beforeEach', 'afterEach', 'after'],45 tests: [{ name: 'test 1', fail: 1 }],46 },47 },48 }, { config: { retries: 1 } })49 .then(snapshotMochaEvents)50 })51 it('test retry with [only]', () => {52 runIsolatedCypress({53 suites: {54 'suite 1': {55 hooks: ['before', 'beforeEach', 'afterEach', 'after'],56 tests: [57 { name: 'test 1' },58 { name: 'test 2', fail: 1, only: true },59 { name: 'test 3' },60 ],61 },62 },63 }, { config: { retries: 1 } })64 .then(snapshotMochaEvents)65 })66 it('can retry from [beforeEach]', () => {67 runIsolatedCypress({68 suites: {69 'suite 1': {70 hooks: [71 'before',72 'beforeEach',73 { type: 'beforeEach', fail: 1 },74 'beforeEach',75 'afterEach',76 'after',77 ],78 tests: [{ name: 'test 1' }],79 },80 },81 }, { config: { retries: 1 } })82 .then(snapshotMochaEvents)83 })84 it('can retry from [afterEach]', () => {85 runIsolatedCypress({86 hooks: [{ type: 'afterEach', fail: 1 }],87 suites: {88 'suite 1': {89 hooks: [90 'before',91 'beforeEach',92 'beforeEach',93 'afterEach',94 'after',95 ],96 tests: [{ name: 'test 1' }, 'test 2', 'test 3'],97 },98 'suite 2': {99 hooks: [{ type: 'afterEach', fail: 2 }],100 tests: ['test 1'],101 },102 'suite 3': {103 tests: ['test 1'],104 },105 },106 }, { config: { retries: 2, isTextTerminal: true } })107 .then(snapshotMochaEvents)108 })109 it('cant retry from [before]', () => {110 runIsolatedCypress({111 suites: {112 'suite 1': {113 hooks: [114 { type: 'before', fail: 1 },115 'beforeEach',116 'beforeEach',117 'afterEach',118 'afterEach',119 'after',120 ],121 tests: [{ name: 'test 1' }],122 },123 },124 }, { config: { retries: 1 } })125 .then(snapshotMochaEvents)126 })127 it('cant retry from [after]', () => {128 runIsolatedCypress({129 suites: {130 'suite 1': {131 hooks: [132 'before',133 'beforeEach',134 'beforeEach',135 'afterEach',136 'afterEach',137 { type: 'after', fail: 1 },138 ],139 tests: [{ name: 'test 1' }],140 },141 },142 }, { config: { retries: 1 } })143 .then(snapshotMochaEvents)144 })145 it('three tests with retry', () => {146 runIsolatedCypress(threeTestsWithRetry, {147 config: {148 retries: 2,149 },150 })151 .then(snapshotMochaEvents)152 })153 describe('screenshots', () => {154 it('retry screenshot in test body', () => {155 let onAfterScreenshot156 runIsolatedCypress({157 suites: {158 'suite 1': {159 tests: [160 {161 name: 'test 1',162 fn: () => {163 cy.screenshot()164 cy.then(() => assert(false))165 },166 eval: true,167 },168 ],169 },170 },171 }, { config: { retries: 1 },172 onBeforeRun ({ autCypress }) {173 autCypress.Screenshot.onAfterScreenshot = cy.stub()174 onAfterScreenshot = cy.stub()175 autCypress.on('after:screenshot', onAfterScreenshot)176 },177 })178 .then(({ autCypress }) => {179 expect(autCypress.automation.withArgs('take:screenshot')).callCount(4)180 expect(autCypress.automation.withArgs('take:screenshot').args).matchDeep([181 { 1: { testAttemptIndex: 0 } },182 { 1: { testAttemptIndex: 0 } },183 { 1: { testAttemptIndex: 1 } },184 { 1: { testAttemptIndex: 1 } },185 ])186 expect(autCypress.automation.withArgs('take:screenshot').args[0]).matchSnapshot({ startTime: match.string, testAttemptIndex: match(0) })187 expect(onAfterScreenshot.args[0][0]).to.matchSnapshot({ testAttemptIndex: match(0) })188 expect(onAfterScreenshot.args[2][0]).to.matchDeep({ testAttemptIndex: 1 })189 })190 })191 it('retry screenshot in hook', () => {192 let onAfterScreenshot193 runIsolatedCypress({194 suites: {195 'suite 1': {196 hooks: [197 {198 type: 'beforeEach',199 fn: () => {200 cy.screenshot()201 cy.then(() => assert(false))202 },203 eval: true,204 },205 ],206 tests: [207 {208 name: 'test 1',209 },210 ],211 },212 },213 }, { config: { retries: 1 },214 onBeforeRun ({ autCypress }) {215 autCypress.Screenshot.onAfterScreenshot = cy.stub()216 onAfterScreenshot = cy.stub()217 autCypress.on('after:screenshot', onAfterScreenshot)218 },219 })220 .then(({ autCypress }) => {221 expect(autCypress.automation.withArgs('take:screenshot')).callCount(4)222 expect(autCypress.automation.withArgs('take:screenshot').args).matchDeep([223 { 1: { testAttemptIndex: 0 } },224 { 1: { testAttemptIndex: 0 } },225 { 1: { testAttemptIndex: 1 } },226 { 1: { testAttemptIndex: 1 } },227 ])228 expect(onAfterScreenshot.args[0][0]).matchDeep({ testAttemptIndex: 0 })229 expect(onAfterScreenshot.args[2][0]).matchDeep({ testAttemptIndex: 1 })230 })231 })232 })233 // https://github.com/cypress-io/cypress/issues/8363234 describe('cleanses errors before emitting', () => {235 it('does not try to serialize error with err.actual as DOM node', () => {236 runIsolatedCypress(() => {237 it('visits', () => {238 cy.visit('/fixtures/dom.html')239 cy.get('#button').should('not.be.visible')240 })241 }, { config: { defaultCommandTimeout: 200 } })242 // should not have err.actual, expected properties since the subject is a DOM element243 .then(snapshotMochaEvents)244 })245 })246 describe('save/reload state', () => {247 const serializeState = () => {248 return getRunState(getAutCypress())249 }250 const loadStateFromSnapshot = (cypressConfig, name) => {251 cy.task('getSnapshot', {252 file: Cypress.spec.name,253 exactSpecName: name,254 })255 .then((state) => {256 cypressConfig[1].state = state257 })258 }259 // NOTE: for test-retries260 describe('retries rehydrate spec state after navigation', () => {261 let realState262 let runCount = 0263 const failThenSerialize = () => {264 if (!runCount++) {265 assert(false, 'stub 3 fail')266 }267 assert(true, 'stub 3 pass')268 return realState = serializeState()269 }270 let runCount2 = 0271 const failOnce = () => {272 if (!runCount2++) {273 assert(false, 'stub 2 fail')274 }275 assert(true, 'stub 2 pass')276 }277 const stub1 = sinon.stub()278 const stub2 = sinon.stub().callsFake(failOnce)279 const stub3 = sinon.stub().callsFake(failThenSerialize)280 let cypressConfig = [281 {282 suites: {283 'suite 1': {284 hooks: [285 'before',286 'beforeEach',287 'afterEach',288 'after',289 ],290 tests: [{ name: 'test 1', fn: stub1 }],291 },292 'suite 2': {293 tests: [294 { name: 'test 1', fn: stub2 },295 { name: 'test 2', fn: stub3 },296 'test 3',297 ],298 },299 },300 }, { config: { retries: 1 } },301 ]302 it('1/2', () => {303 runIsolatedCypress(...cypressConfig)304 .then(shouldHaveTestResults(4, 0))305 .then(() => {306 expect(realState).to.matchSnapshot(cleanseRunStateMap, 'serialize state - retries')307 })308 })309 it('2/2', () => {310 loadStateFromSnapshot(cypressConfig, 'serialize state - retries')311 runIsolatedCypress(...cypressConfig)312 .then(shouldHaveTestResults(4, 0))313 .then(() => {314 expect(stub1).to.calledOnce315 expect(stub2).to.calledTwice316 expect(stub3).calledThrice317 })318 })319 })320 })...

Full Screen

Full Screen

micoocypress.test.js

Source:micoocypress.test.js Github

copy

Full Screen

...79 const micoocypressFunction = micoocypress.__get__("micoocypress"); 80 micoocypress.__with__({on: on})(() => {81 micoocypressFunction(on, micooption);82 expect(on).toHaveBeenCalledTimes(2);83 expect(on.mock.calls[0][0]).toEqual('after:screenshot', details => onAfterScreenshot(details));84 expect(on.mock.calls[1][0]).toEqual('after:run', async results => await onAfterRun(results, micooption, cypressOption));85 });86 })87 it("onAfterScreenshot collect screenshots", () => {88 const details = {};89 const onAfterScreenshot = micoocypress.__get__("onAfterScreenshot");90 micoocypress.__with__({collectScreenshots: jest.fn()})(async () => {91 onAfterScreenshot(details);92 expect(collectScreenshots).toHaveBeenCalledWith(details);93 });94 })95 it("onAfterRun not to trigger visual testing when triggerVisualTesting is disabled", () => {96 const results = {};97 const cypressOption = { triggerVisualTesting: false };98 const onAfterRun = micoocypress.__get__("onAfterRun");99 micoocypress.__with__({triggerVisualTesting: jest.fn()})(async () => {100 onAfterRun(results, micooption, cypressOption);101 expect(triggerVisualTesting).not.toHaveBeenCalled();102 });103 })104 it("onAfterRun trigger visual testing even not all tests passed", () => {105 const results = {};...

Full Screen

Full Screen

screenshot.js

Source:screenshot.js Github

copy

Full Screen

...168 onBeforeScreenshot ($el) {169 return defaults.onBeforeScreenshot($el)170 },171 onAfterScreenshot ($el, results) {172 return defaults.onAfterScreenshot($el, results)173 },174 defaults (props) {175 const values = validate(props, 'Cypress.Screenshot.defaults')176 return _.extend(defaults, values)177 },178 validate,...

Full Screen

Full Screen

toMatchImageSnapshot.js

Source:toMatchImageSnapshot.js Github

copy

Full Screen

1/* globals cy */2/* eslint-env browser */3const { MATCH_IMAGE } = require('../tasks/taskNames');4const getTaskData = require('../utils/commands/getTaskData');5const logMessage = require('../utils/commands/logMessage');6const { NO_LOG } = require('../constants');7const { COMMAND_MATCH_IMAGE_SNAPSHOT: commandName } = require('./commandNames');8const getImageData = require('../utils/image/getImageData');9const {10 getImageConfig,11 getScreenshotConfig,12 getCustomName,13 getCustomSeparator,14} = require('../config');15function afterScreenshot(taskData) {16 return ($el, props) => {17 // See this url for contents of `props`:18 // https://docs.cypress.io/api/commands/screenshot.html#Get-screenshot-info-from-the-onAfterScreenshot-callback19 const win = $el.get(0).ownerDocument.defaultView;20 taskData.image = getImageData(props, win.devicePixelRatio);21 taskData.isImage = true;22 delete taskData.subject;23 };24}25async function toMatchImageSnapshot(subject, commandOptions) {26 const options = getImageConfig(commandOptions);27 const customName = getCustomName(commandOptions);28 const customSeparator = getCustomSeparator(commandOptions);29 const taskData = await getTaskData({30 commandName,31 options,32 customName,33 customSeparator,34 subject,35 });36 const screenShotConfig = getScreenshotConfig(commandOptions);37 const afterScreenshotFn = afterScreenshot(taskData);38 if (screenShotConfig.onAfterScreenshot) {39 const afterScreenshotCallback = screenShotConfig.onAfterScreenshot;40 screenShotConfig.onAfterScreenshot = (...args) => {41 afterScreenshotFn.apply(this, args);42 afterScreenshotCallback.apply(this, args);43 };44 } else {45 screenShotConfig.onAfterScreenshot = afterScreenshotFn;46 }47 return cy48 .wrap(subject, NO_LOG)49 .screenshot(taskData.snapshotTitle, screenShotConfig)50 .then(() => cy.task(MATCH_IMAGE, taskData, NO_LOG).then(logMessage));51}...

Full Screen

Full Screen

after_screenshot_spec.js

Source:after_screenshot_spec.js Github

copy

Full Screen

1it('cy.screenshot() - replacement', () => {2 cy.screenshot('replace-me', { capture: 'runner' }, {3 onAfterScreenshot (details) {4 expect(details.path).to.include('screenshot-replacement.png')5 expect(details.size).to.equal(1047)6 expect(details.dimensions).to.eql({ width: 1, height: 1 })7 },8 })9})10it('cy.screenshot() - ignored values', () => {11 cy.screenshot('ignored-values', { capture: 'runner' }, {12 onAfterScreenshot (details) {13 expect(details.path).to.include('ignored-values.png')14 expect(details.multipart).to.be.false15 expect(details.name).to.equal('ignored-values')16 },17 })18})19it('cy.screenshot() - invalid return', () => {20 cy.screenshot('invalid-return', { capture: 'runner' }, {21 onAfterScreenshot (details) {22 expect(details.path).to.include('invalid-return.png')23 },24 })25})26it('failure screenshot - rename', () => {27 throw new Error('test error')...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = (on, config) => {2 on('after:screenshot', (details) => {3 console.log('details', details)4 })5}6module.exports = (on, config) => {7 on('after:screenshot', (details) => {8 console.log('details', details)9 })10}11require('../test.js')12require('../test.js')13require('../test.js')14require('../test.js')15require('../test.js')16require('../test.js')17require('../test.js')18require('../test.js')19require('../test.js')20require('../test.js')21require('../test.js')22require('../test.js')23require('../test.js')24require('../test.js')25require('../test.js')26require('../test.js')27require('../test.js')28require('../test.js')29require('../test.js')30require('../test.js')

Full Screen

Using AI Code Generation

copy

Full Screen

1afterEach(function () {2 if (this.currentTest.state === 'failed') {3 Cypress.runner.stop()4 }5})6afterEach(function () {7 if (this.currentTest.state === 'failed') {8 Cypress.runner.stop()9 }10})11afterEach(function () {12 if (this.currentTest.state === 'failed') {13 Cypress.runner.stop()14 }15})16afterEach(function () {17 if (this.currentTest.state === 'failed') {18 Cypress.runner.stop()19 }20})21afterEach(function () {22 if (this.currentTest.state === 'failed') {23 Cypress.runner.stop()24 }25})26afterEach(function () {27 if (this.currentTest.state === 'failed') {28 Cypress.runner.stop()29 }30})31afterEach(function () {32 if (this.currentTest.state === 'failed') {33 Cypress.runner.stop()34 }35})36afterEach(function () {37 if (this.currentTest.state === 'failed') {38 Cypress.runner.stop()39 }40})41afterEach(function () {42 if (this.currentTest.state === 'failed') {43 Cypress.runner.stop()44 }45})46afterEach(function () {47 if (this.currentTest.state === 'failed') {48 Cypress.runner.stop()49 }50})51afterEach(function () {52 if (this.currentTest.state === 'failed') {53 Cypress.runner.stop()54 }55})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('afterScreenshot', (test, name) => {2 return cy.task('afterScreenshot', {3 })4});5Cypress.on('test:after:run', (test, runnable) => {6 if (test.state === 'failed') {7 cy.afterScreenshot(test, 'failed').then((options) => {8 addContext({ test }, options.path);9 });10 }11});12const { afterScreenshot } = require('cypress-audit/src/plugin');13module.exports = (on, config) => {14 on('task', {15 });16};17require('cypress-audit/commands');18require('cypress-audit/src/plugin');19describe('Test', () => {20 it('Test', () => {21 cy.get('input[name="q"]').type('cypress');22 cy.get('input[name="btnK"]').click();23 cy.get('.hero-title').should('contain', 'Cypress');24 });25});26{27 "reporterOptions": {28 }29}30{31 "scripts": {32 },33 "devDependencies": {34 }35}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Cypress Screenshot', function() {2 it('screenshot', function() {3 cy.screenshot()4 })5})6{7 "env": {8 }9}10describe('Cypress Screenshot', function() {11 it('screenshot', function() {12 cy.screenshot()13 })14})15{16 "env": {17 }18}19describe('Cypress Screenshot', function() {20 it('screenshot', function() {21 cy.screenshot()22 })23})24{25 "env": {26 }27}

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.on('after:screenshot', (details) => {2 console.log('Screenshot saved to', path)3})4Cypress.on('after:screenshot', (details) => {5 console.log('Screenshot saved to', path)6})7Cypress.on('after:screenshot', (details) => {8 console.log('Screenshot saved to', path)9})10Cypress.on('after:screenshot', (details) => {11 console.log('Screenshot saved to', path)12})

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