赛普拉斯-检查文件是否已下载

时间:2020-03-03 14:50:21

标签: automation automated-tests cypress

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

用户界面中的按钮是我点击的按钮,应用会生成并下载一些PDF。

我需要检查此文件是否会生成(和下载)。

赛普拉斯可以这样做吗?

3 个答案:

答案 0 :(得分:3)

我建议您看一下HTTP响应正文。 您可以使用cy.server().route('GET', 'url').as('download')得到响应(如果您不知道这些方法,请查看cypress文档)。

并捕获响应以验证主体不为空:

cy.wait('@download')
    .then((xhr) => {
        assert.isNotNull(xhr.response.body, 'Body not empty')
    })

或者,如果在下载成功后有一个弹出窗口宣布成功,您也可以验证弹出窗口的存在:

cy.get('...').find('.my-pop-up-success').should('be.visible')

最好

答案 1 :(得分:2)

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);
    }, 10);
  });
};

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);
});

答案 2 :(得分:-1)

您无法使用Cypress进行此操作,因为Javascript仅在浏览器上有效。您无法访问本地文件来检查其是否已下载。

This link might help you to have better understanding of the concept