Laxmi
Laxmi

Reputation: 13

converting downloaded file to pdf throws error in cypress

in plugins file cypress

 on('task', {
        readFile(filename) {
          if (fs.existsSync(filename)) {
            return pdf.parse(fs.readFileSync(filename, 'utf8'));
          }
          return null;
        },
      });

and in my code i am using readfile as:

 isUserRemovedFromExport(status: string, trainee: string, document: string) {
        const downloadsFolder = Cypress.config('downloadsFolder');
        usersUtil.getCurrentCompany().then((company) => {
          const filename = `${dates.getShortFormattedToday()}-${company.name}-document-${document}-training-data.pdf`;
          const downloadFileName = path.join(downloadsFolder, filename);
          cy.readFile(downloadFileName).should('have.text', trainee);
        });
      }
    }

when i do so i get following error

enter image description here

enter image description here

I have also tried :

 on('task', {
    getPdfContent(obj) {
      const pdfPathname = path.join(Cypress.config('downloadsFolder'), obj);
      return new Promise((resolve, reject) => {
        try {
          const data = pdf.parse(fs.readFileSync(pdfPathname));
          resolve(data);
        } catch (e) {
          reject(e);
        }
      });
    },
  });

but the above block throws error at cy.task as cypress not defined

Upvotes: 0

Views: 322

Answers (1)

Fody
Fody

Reputation: 31954

You aren't actually calling the task.

cy.readFile() is a built-in command, not your custom task.

Try this

cy.task('readFile', downloadFileName)
  .should('have.text', trainee);

The 2nd version looks ok too, but running in Node it has no access to Cypress as you mentioned.

You can pass two params in obj

test

const filename = `${dates.getShortFormattedToday()}-${company.name}-document-${document}-training-data.pdf`;

// Make a single parameter for task
const params = {
  filename, 
  downloadsFolder: Cypress.config('downloadsFolder')
}

cy.task('getPdfContent', params).should('have.text', trainee)

task

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

on('task', {
    getPdfContent(obj) {

      const { 
        filename,             // should be small 'n'
        downloadsFolder 
      } = obj;

      const pdfPathname = path.join(downloadsFolder, filename);
      return new Promise((resolve, reject) => {
        try {

          // from https://www.npmjs.com/package/pdf-parse
          pdf(fs.readFileSync(pdfPathname)).then(function(data) {
            resolve(data);
          })

        } catch (e) {
          reject(e);
        }
      });
    },
  });

Notes

  • can't use path.join() in the test because it's Node command.
  • task can only receive one parameter, so combined the downloadsFolder and fileName in single object.

Upvotes: 1

Related Questions