JohnPix
JohnPix

Reputation: 1843

Parse pdf with Cypress

I am trying to parse pdf with the code below, I added the code that parse file in plugins/index.js and test.spec.js, but when I try to handle the promise with .then() instead of parsed text I get [object Promise] in console. How to handle the promise and get plain text?

index.js

const fs = require('fs')
const path = require('path')
const pdf = require('pdf-parse');

const repoRoot = path.join(__dirname, '..', '..')

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 String(parsePdf(pdfName))
    }
  })
}

test.spec.js

it('Parse PDF', ()=>{
        cy.task('getPdfContent', 'test.pdf').then((content) => 
            console.log(content)
          )
    })

Upvotes: 4

Views: 3841

Answers (1)

user14783414
user14783414

Reputation:

You can just return the promise from the task, see Waiting for Promises

return a promise to cy.then()
that is awaited until it resolves

module.exports = (on, config) => {
  on('task', {
    getPdfContent(pdfName) {
      return parsePdf(pdfName)   
    }
  })
}
it('Parse PDF', ()=>{
  cy.task('getPdfContent', 'test.pdf').then((content) => 
    console.log(content)
    /*
     {
       numpages: 1, 
       numrender: 1, 
       info: {
         CreationDate: "…"
         Creator: "…"
         IsAcroFormPresent: false
         IsXFAPresent: false
         ModDate: "…"
         ...
       }, 
       metadata: null, 
       text: "…"
       version: "…"
   */
  )
})

Upvotes: 3

Related Questions