Testing printing a page from a webapp (Cypress, Jest, Storybook???)

1.3k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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)')
})