首页 > 解决方案 > 赛普拉斯 - 如何验证下载的文件是否包含动态名称?

问题描述

在 cypress 中,我下载的 xlsx 文件总是以“ABC”开头,然后是一些动态 ID。如何验证文件是否已成功下载并且还包含该动态名称?其次,如果下载的文件类似于“69d644353f126777.xlsx”,那么当名称中的所有内容都是动态的时,我如何验证文件是否已下载。

提前致谢。

标签: cypress

解决方案


建议自己的一种方法是使用任务查询下载文件夹,

/cypress/plugins/index.js

const fs = require('fs');

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

测试

cy.task('downloads', 'my/downloads/folder').then(before => {

  // do the download

  cy.task('downloads', 'my/downloads/folder').then(after => {
    expect(after.length).to.be.eq(before.length +1)  
  })
})

如果您无法将下载内容定向到项目本地的文件夹,请提供完整路径。Node.js(即 Cypress 任务)可以完全访问文件系统。


要获取新文件的名称,请使用过滤器并获取结果中的第一个(也是唯一一个)项目。

const newFile = after.filter(file => !before.includes(file))[0]

 

推荐阅读