Let's take Filip Hric's Testing a PDF file with Cypress and see if we can play with it a little. In his example, Filip downloads a PDF and reads it as text using pdf-parse NPM utility. Then test then checks if the PDF text contains a sentence we expect it to have.
1 | it('downloads a simple PDF file', () => { |
The cy.task
calls the method defined in the cypress.config.ts
file that calls the Node code to parse the PDF file already on disk
1 | const { defineConfig } = require('cypress') |
1 | const fs = require('fs') |
🎁 I forked Filip's repo filiphric/testing-pdf-with-cypress into mine bahmutov/testing-pdf-with-cypress. In this blog post I show my versions and tweaks to the original specs.
PDF to HTML
But what if we could see the PDF file? What if we could load PDF into the browser and then query it using "normal" Cypress commands like cy.contains
, cy.get
, etc? Wouldn't that be cool? We would see the PDF contents right in the screenshots and videos taken during the cypress run
.
Let's do this!
Let's install pdf2html and call it via a task to get HTML of the PDF
1 | const { defineConfig } = require('cypress') |
Instead of the readPdf
task, let's call toHtml
task which should yield the PDF converted into HTML string
1 | it('converts downloaded PDF to HTML', () => { |
Ok, it works
Ughh, I don't like that long HTML string in the Cypress Command Log, even if the assertion is green. Is there any place better to drop the HTML in?
Write HTML to the document
Just like I have done in my Full End-to-End Testing for Your HTML Email Workflows presentation and the blog post Testing HTML Emails using Cypress, let's write the produced HTML string into the document
object - then the browser will show it.
1 | it('converts downloaded PDF to HTML', () => { |
Notice how we are using cy.contains
command to confirm the downloaded "simple.pdf" file has the text we are looking for?
Tip: if you want to see a small PDF better, change the viewport after writing the HTML string with cy.viewport
command
Complex PDF
Let's click the "complex.pdf" and confirm its contents
1 | it('tests the complex pdf', () => { |
Hmm, I promised to be able to see the PDF file and test it using Cypress commands, I haven't promised to make it pretty.