Cypress-检查文件是否已下载 [英] Cypress - check if the file is downloaded

查看:28
本文介绍了Cypress-检查文件是否已下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试检查文件是否已下载时遇到一些问题。

单击按钮将生成PDF文件并开始下载。

我需要检查它是否正常工作。

Cypress可以这样做吗?

cypress/plugins/index.js

推荐答案
    const path = require('path');
    const fs = require('fs');
    
    const downloadDirectory = path.join(__dirname, '..', 'downloads');
    
    const findPDF = (PDFfilename) => {
      const PDFFileName = `${downloadDirectory}/${PDFfilename}`;
      const contents = fs.existsSync(PDFFileName);
      return contents;
    };
    
    const hasPDF = (PDFfilename, ms) => {
      const delay = 10;
      return new Promise((resolve, reject) => {
        if (ms < 0) {
          return reject(
            new Error(`Could not find PDF ${downloadDirectory}/${PDFfilename}`)
          );
        }
        const found = findPDF(PDFfilename);
        if (found) {
          return resolve(true);
        }
        setTimeout(() => {
          hasPDF(PDFfilename, ms - delay).then(resolve, reject);
        }, delay);
      });
    };
    
    module.exports = (on, config) => {
      require('@cypress/code-coverage/task')(on, config);
      on('before:browser:launch', (browser, options) => {
        if (browser.family === 'chromium') {
          options.preferences.default['download'] = {
            default_directory: downloadDirectory,
          };
          return options;
        }
        if (browser.family === 'firefox') {
          options.preferences['browser.download.dir'] = downloadDirectory;
          options.preferences['browser.download.folderList'] = 2;
          options.preferences['browser.helperApps.neverAsk.saveToDisk'] =
            'text/csv';
          return options;
        }
      });
    
      on('task', {
        isExistPDF(PDFfilename, ms = 4000) {
          console.log(
            `looking for PDF file in ${downloadDirectory}`,
            PDFfilename,
            ms
          );
          return hasPDF(PDFfilename, ms);
        },
      });
    
      return config;
    };

integration/pdfExport.spec.js

    before('Clear downloads folder', () => {
       cy.exec('rm cypress/downloads/*', { log: true, failOnNonZeroExit: false });
    });
        
    it('Should download my PDF file and verify its present', () => {
        cy.get('ExportPdfButton').click();
        cy.task('isExistPDF', 'MyPDF.pdf').should('equal', true);
    });

这篇关于Cypress-检查文件是否已下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆