Log HTML
Cypress automatically includes the jQuery library and exposes it's methods - this includes html() which can give you an element's HTML content as a string. If you have console.log() set-up (also see below) then you can then print an element's HTML string to the console with console.log()
, e.g.:
cy.get('body').invoke('html').then((val) => console.log(JSON.stringify(val)))
Log only on test failures
If you don't want to flood your test output all the time and only want to print that HTML when a test fails, you can bind to Cypress events such as 'fail' with cy.on('fail', ...)
within the specific tests. If you want this automatically for all tests, then you can rather use Cypress.on('fail', ...)
which you would need to put in your supportFile, possibly as follows:
/**
* Place in supportFile, e.g. cypress/support/e2e.js
*/
// Setup code to run before each test
Cypress.on('fail', (err, runnable) => {
// always print the full page DOM whenever an error occurs
console.log(Cypress.$('body').html())
// re-throw error so test still fails
throw err
})
Console logging
See this question for more details on logging to the console in Cypress. A quick summary of what worked for me was to add the following to my cypress.config.js
:
const { defineConfig } = require('cypress')
module.exports = defineConfig({
e2e: {
// Other settings
...
// Enable console.log() in tests
setupNodeEvents(on, config) {
on('task', {
log(message) {
console.log(message)
return null
}
})
},
}
})
However, console.log()
's output won't necessarily be output to the terminal, so you might need to set the ELECTRON_ENABLE_LOGGING
environment variable to 1
, e.g. you could run Cypress as follows:
ELECTRON_ENABLE_LOGGING=1 npx cypress run