1

Let's say you just received the requirement about implementing a new feature in your webapp which should print on paper a section of that page. The requirement talks about optional elements to be part or not of the printed product.

What is the best possible way of testing this feature automatically? I am aware that once you invoke the printing command that's out of the Browsers' scope so it's not possible to write a perfect automated test so the question is oriented to find the best "good enough" approach, hopefully something better than only spying on window.print() to assert it was called.

Miles
  • 83
  • 4
  • This looks promising https://github.com/RRMoelker/print-css-toggle Enables `` Disables `` Enabling `@media print { ... }` css – Michael Dimmitt Aug 18 '21 at 16:28
  • I have not tried but need to test on an example project by using @media print { } styles. another link on designing for print page: https://www.smashingmagazine.com/2015/01/designing-for-print-with-css/ – Michael Dimmitt Aug 18 '21 at 16:29

1 Answers1

3

There's an emulation mode in Chrome, see using-chromes-element-inspector-in-print-preview-mode.

You can turn it on with Cypress, see Using Chrome Debugger Protocol from Cypress.

HTML

<body>
  <h1>Title</h1>
  <style>
    @media screen {
      h1 {
        color: red;
      }
    }
    @media print {
      h1 {
        color: blue;
      }
    }
  </style>
</body>

Example test

Cypress.Commands.add('setCssMedia', (media) => {
  cy.log(`Setting CSS media to ${media}`)
  Cypress.automation('remote:debugger:protocol', {
    command: 'Emulation.setEmulatedMedia',
    params: {
      media
    },
  })
})

it('tests for print and screen media', () => {

  cy.setCssMedia('print')
  cy.get('h1').should('have.css', 'color', 'rgb(0, 0, 255)')

  cy.setCssMedia('screen')
  cy.get('h1').should('have.css', 'color', 'rgb(255, 0, 0)')
})

user16695029
  • 3,365
  • 5
  • 21