Dhamo
Dhamo

Reputation: 1251

Cypress identify the downloaded file using regex

I have one scenario where I have to verify the downloaded text file's data against an API response.

Below is the code that I have tried.

Test:

const path = require('path')
const downloadsFolder = Cypress.config('downloadsFolder')
cy.task('deleteFolder', downloadsFolder)
const downloadedFilename = path.join(downloadsFolder, 'ABCDEF.txt')//'*.txt'
....
  cy.get('@portmemo').its('response.body')
    .then((response) => {
      var json = JSON.parse(response);
      const resCon = json[0].content.replaceAll(/[\n\r]/g, '');
      cy.readFile(downloadedFilename).then((fc) => {
        const formatedfc = fc.replaceAll(/[\n\r]/g, '');
        cy.wrap(formatedfc).should('contains', resCon)
      })
    })

Task in /cypress/plugins/index.js

const { rmdir } = require('fs')

module.exports = (on, config) => {
    console.log("cucumber started")


    on('task', {
        deleteFolder(folderName) {
            return new Promise((resolve, reject) => {
                rmdir(folderName, { maxRetries: 5, recursive: true }, (err) => {
                    if (err) {
                        console.error(err);
                        return reject(err)
                    }
                    resolve(null)
                })
            })
        },
    })

When I have the downloadedFilename as 'ABCDEF.txt', it works fine [I have hard coded here]. But I need some help to get the (dynamic) file name as it changes every time [eg.: AUADLFA.txt, CIABJPT.txt, SVACJTM.txt, PKPQ1TM.txt & etc.,].

I tried to use '.text' but I get 'Timed out retrying after 4000ms: cy.readFile("C:\Repositories\xyz-testautomation\cypress\downloads/.txt") failed because the file does not exist error.

I referred to this doc as well but no luck yet.

What is the right way to use regex to achieve the same? Also wondering is there a way to get the recently downloaded file name?

Upvotes: 3

Views: 6249

Answers (1)

user9161752
user9161752

Reputation:

You can make use of the task shown in this question How can I verify if the downloaded file contains name that is dynamic

/cypress/plugins/index.js

const fs = require('fs');

on('task', {
  downloads:  (downloadspath) => {
    return fs.readdirSync(downloadspath)
  }
})

This returns a list of the files in the downloads folder.

Ideally you'd make it easy on yourself, and set the trashAssetsBeforeRuns configuration. That way, the array will only contain the one file and there's no need to compare arrays before and after the download.

(Just noticed you have a task for it).

Upvotes: 3

Related Questions