Cypress - How to Verify Data from a Pdf File Using Cypress Command
Below Is My Code in Cypress. How to Print 'Pdf' Content and Verify Content Using Cypress. Contains Or. Eq? When I Run the Code It Prints Object{6} but I Want...
Below is my code in cypress. How to print 'pdf' content and verify content using cypress .contains or .eq? when I run the code it prints object{6} but I want to print my pdf file content. I would really appreciate the help.
**Plugins/index.js:**
const fs = require('fs')
const pdf = require('pdf-parse')
const path = require('path')
const repoRoot = path.join("C:/Users/XXXXX/Downloads/loginCy-excel")
const parsePdf = async (pdfName) => {
const pdfPathname = path.join(repoRoot, pdfName)
let dataBuffer = fs.readFileSync(pdfPathname);
return await pdf(dataBuffer)
}
module.exports = (on, config) => {
on('task', {
getPdfContent (pdfName) {
return parsePdf(pdfName)
},
})
}
**cypress spec file has these code:**
it('tests a pdf', () => {
cy.task('getPdfContent', 'sample.pdf').then(content => {
cy.log(content)
})
})
2 Answers
Anyone struggling with testing PDF files with cypress can refer to these two very good blog posts precisely on this topic:
It wasn't asked in this question, but here is a little addition from me on how to download files (was tested on PDFs) from a URL:
cy.request({
url: '<file url>',
gzip: false,
encoding: 'base64',
}).then((response) => {
cy.writeFile(
Cypress.config('downloadsFolder') + '/<name of the file>.pdf',
response.body,
{ encoding: 'base64' }
);
pdf method will return an object, so I guess cy.log() can't print it like that. If you want to see what the function gathered in your pdf file, you can stringify the result:
cy
.log(JSON.stringify(content));
If you want to get only text from your pdf, you need to work with text property:
cy
.log(content.text);