trickster
trickster

Reputation: 99

Configure screenshot folder in Cypress

I am using Cypress as my user interface test automation framework.
Currently my folder structure for spec file (logical organization of test files) is:

~/myAccount/header/header.spec.js

~/myAccount/footer/footer.spec.js

~/myAccount/mainTabs/home.spec.js

and so on...
Now when I configure my screenshot folder in cypress.json to screenshots and save screenshots of failed test cases, cypress internally creates a folder structure inside screenshots folder. For instance if a test fails in footer.spec.js, it saves the screenshot in

~/screenshots/myAccount/footer/footer.spec.js

I want to get rid of this recursive folder structure and save all screenshots inside screenshots folder (so that I can easily access these screenshots and add it to my mochawesome report).
Is there any way to do it ? Any help will be appreciated and let me know if I was unable to put my question properly. I am willing to add more information.

Upvotes: 2

Views: 8850

Answers (1)

kuceb
kuceb

Reputation: 18043

Yes, you can use the Cypress screenshot API:

for example:

// cypress/plugins/index.js

const fs = require('fs')

module.exports = (on, config) => {
  on('after:screenshot', (details) => {
    // details will look something like this:
    // {
    //   size: 10248
    //   takenAt: '2018-06-27T20:17:19.537Z'
    //   duration: 4071
    //   dimensions: { width: 1000, height: 660 }
    //   multipart: false
    //   pixelRatio: 1
    //   name: 'my-screenshot'
    //   specName: 'integration/my-spec.js'
    //   testFailure: true
    //   path: '/path/to/my-screenshot.png'
    //   scaled: true
    //   blackout: []
    // }

    // example of renaming the screenshot file

    const newPath = '/new/path/to/screenshot.png'

    return new Promise((resolve, reject) => {
      fs.rename(details.path, newPath, (err) => {
        if (err) return reject(err)

        // because we renamed/moved the image, resolve with the new path
        // so it is accurate in the test results
        resolve({ path: newPath })
      })
    })
  })
}

You could also create symlinks if you wanted the image in two places, for example.

Upvotes: 8

Related Questions