javascript 如何在cypress.config.js中的cy.task()函数中添加wait,如validateZipFile和getZipFileSize

kxe2p93d  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(162)

如何在cypress.config.js文件中的下列cy.task()函数(如validateZipFilegetZipFileSize)中添加等待?

test.spec.js

cy.get('button[type="submit"]').contains("Download").click({force:true});
helperFunctions.validateZip("Booking Results Resource Pack - Task");

//helperFunctions.js

validateZip (text) {
    const dfilename = text.replace(/-|_|\s/g,"");
    const downloadedFilename = dfilename+"ZipFile.zip";
   
    cy.task('getZipFileSize', downloadedFilename)
    .should('eq', 6149237)

    cy.task('validateZipFile', downloadedFilename)
    .should('deep.eq', [
      '__Booking-Resource__Question-Cards__Booking_BW.pdf', 
      '__Booking-Resource__Question-Cards__Booking-Colour.pdf'
    ]);
    
  }

cypress.config.js

const AdmZip = require("adm-zip");
    
    const { defineConfig } = require('cypress')
    
    module.exports = defineConfig({
       e2e: {
        setupNodeEvents(on, config) {
          .....
    
    
            on('task', {
            validateZipFile: filename => {
              const downloadsFolder = config.downloadsFolder
              return  validateZipFile(path.join(downloadsFolder, filename))
            },
            getZipFileSize: filename => {
              const downloadsFolder = config.downloadsFolder
              const stats = fs.statSync(path.join(downloadsFolder, filename))
              return stats.size
            }
          });
    
          return config;
        },
        baseUrl: "https://staging-qa.someurl.com/",
        specPattern: "cypress/e2e/**/*.spec.{js,jsx,ts,tsx}",
      },
    })

 function validateZipFile(filename) {
  const zip = new AdmZip(filename)
  const zipEntries = zip.getEntries()
  const names = zipEntries.map(entry => entry.entryName).sort()
  return names
}
bsxbgnwa

bsxbgnwa1#

假设网页上没有任何内容指示下载已完成:
这是Yevhen Laichenkov在基辅的文章,Cypress: How to verify that file is downloaded with cy-verify-downloads
他提到了大文件和cy.readFile()的内存问题,并构建了一个cy-verify-downloads库。

cypress.config.js

const { verifyDownloadTasks } = require('cy-verify-downloads');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', verifyDownloadTasks);
    },
  },
})

帮助者

require('cy-verify-downloads').addCustomCommand()

validateZip (text) {
    const dfilename = text.replace(/-|_|\s/g,"");
    const downloadedFilename = dfilename+"ZipFile.zip";
   
    cy.verifyDownload(downloadedFilename );

    cy.task('getZipFileSize', downloadedFilename)
    .should('eq', 6149237)

    cy.task('validateZipFile', downloadedFilename)
    .should('deep.eq', [
      '__Booking-Resource__Question-Cards__Booking_BW.pdf', 
      '__Booking-Resource__Question-Cards__Booking-Colour.pdf'
    ]);
  }

测试(无变化)

cy.get('button[type="submit"]').contains("Download").click({force:true});
helperFunctions.validateZip("Booking Results Resource Pack - Task");

轮询下载

或者,您可以基于poll nodejs库构建新任务

const fs = require('fs')
const poll = require('poll')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        poll: (filename) => {
          let fileExists = false;
          poll(
            () => { fileExists = fs.existsSync(filename) }, 
            100,                                            // check every 100ms
            () => fileExists                                // stop when file exists
          )
        }
      });
    },
  },
})

测试

cy.get('button[type="submit"]').contains("Download").click({force:true});

cy.task('poll', filename, {timeout: 30_000})   // 30 seconds to wait, then fail

helperFunctions.validateZip("Booking Results Resource Pack - Task");
jchrr9hc

jchrr9hc2#

你可以通过创建一个像这样的函数并在任务开始时调用它来避免使用第三方库:

const fs = require('fs');

const sleep = time => new Promise(res => {
    setTimeout(res, time);
});

const verifyFileDownloaded = async filePath => {
    const MAX_POLLS = 10;
    const POLL_INTERVAL = 1000;
    
    for (let i = 0; i < MAX_POLLS; i++) {
        if (fs.existsSync(filePath)) {
            return;
        }

        await sleep(POLL_INTERVAL);
    }

    throw new Error(`Failed to detect the file at the path "${filePath}" within the timeout of ${POLL_INTERVAL / 1000 * MAX_POLLS} seconds`);
}

相关问题