Is there a way I can extract data from the node using Cypress?

199 Views Asked by At

I'm trying to find a way I can extract this information in to my test or print it out somewhere. In it's current format it just says you have 3 accessibility issues. It's not very descriptive, so I want to extract the below image somehow as you can see in the nodes it gives me the exact element to fix. So how would one extract that information to make it a more useful test. I've had a look at the cypress documentation and I've not seen anything that might be useful so is it possible?

describe('Womens T20 Cricket Test',() => {
it('Should log any accssibility failures critical impact on a competition page',() => {
    cy.visit('https://www.skysports.com/cricket/ICC-Womens-World-T20');
    cy.iframe('#sp_message_iframe_758392').find('.sp_message-accept-button').should('be.visible').click()

    cy.injectAxe();
    cy.checkA11y(null, { includedImpacts: ['critical', 'serious', 'moderate']})
    });
});

Image of accessibility issues

1

There are 1 best solutions below

4
On

What you want to do is a bit difficult, since the highlights are the result of manually selecting the log entry. You could try the screenshot command but I think it would miss some details.

Maybe a better approach is to stop cy.checkA11y() failing the test, like so

// Define at the top of the spec file or just import it
function terminalLog(violations) {
  cy.task(
    'log',
    `${violations.length} accessibility violation${
      violations.length === 1 ? '' : 's'
    } ${violations.length === 1 ? 'was' : 'were'} detected`
  )
  // pluck specific keys to keep the table readable
  const violationData = violations.map(
    ({ id, impact, description, nodes }) => ({
      id,
      impact,
      description,
      nodes: nodes.length
    })
  )

  cy.task('table', violationData)
}

// Then in your test...
it('Logs violations to the terminal', () => {
  cy.checkA11y(null, null, terminalLog)
})

and the task definition is

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        log(message) {
          console.log(message)

          return null
        },
        table(message) {
          console.table(message)

          return null
        }
      })
    },
  },
})

This is the reference code Using the violationCallback argument. Note the task setup given is out of date, you should follow my example.

Results

enter image description here