【发布时间】:2022-01-12 19:12:50
【问题描述】:
我有一种情况,我必须使用赛普拉斯命令验证下载文件的数据。文件类型:- pdf、word、excel。 我有被调用的服务器 API 操作的 URL,作为响应,它返回 pdf 文件。 我需要使用 Cypress 命令和 Typescript(插件和打字)来实现。
我能够获得下载的状态,甚至 response.body 也有一些文本,但它需要一些解析器来解析响应正文。 下面是我尝试过的代码。
const oReq = new XMLHttpRequest();
oReq.open("GET", href as string, true);
oReq.responseType = "arraybuffer";
oReq.onload = () => {
if (oReq.readyState === oReq.DONE) {
if (oReq.status === 200) {
// tried parsing the response.
// looking for any parser which can parse the given reponse body into Text or json
}
}
}
cy.request(href).then((response) => {
expect(response.status).to.equal(200);
expect(response.body).not.to.null;
const headerValue = response.headers["content-disposition"];
// expect(headerValue).to.equal("attachment; filename=ExperimentEntityList.<FileExtension-PDF | XLSX | DOCX>");
/// have tried with YAML parser and the "FS" module that cypress and ends up in different console error
// YAML parser gives consoole error about unidentified character "P".
// FS module code is shown below
});
import * as fs from "fs";
function GetPDFContent()
{
// throws console that fs object doesn't have readFile and same with readFileSync method.
fs.readFile("url")..
fs.readFileSync("url")..
}
要求:
1) 读取 PDF 文件的内容
2) 读取 XLS(x) 文件的内容
3) 读取 doc(x) 文件的内容。
在 cypress 自动化脚本的 typescript 中读取 PDF 和 DOc(x) 文件的内容时没有成功。浏览互联网上的各种博客,安装 pdfparser、pdfreader、yaml 解析器、filereader 等等。但是,它们都不起作用。我已经使用上面提到的代码来读取文件。 并检查相应命令的书面注释。
对于 xlsx 文件,我通过使用解析 Response.body 的 XSLX 解析器插件找到了解决方案,我可以迭代并获取内容。 我正在为 PDF 和 Doc(x) 文件寻找类似的解析器。
任何人都知道这件事。请分享!!!
注意:括号或语法不是问题。如果在上面的示例代码中找到,那么它会在复制/粘贴过程中丢失。
编辑:
我找到了使用 Cypress commadns 读取和验证 PDF 文件内容的解决方案。感谢理查德·马森, @Richard:但是,问题是当我有 PDF 文件的完整 url 时。喜欢-http://domainname/upload/files/pdf/pdfname.pdf。然后我可以阅读内容并验证它。但是,如果我的问题是我有一个像“http://domainname/controller/action?pdf=someid”这样的 url,它返回 pdf 文件响应并且节点命令没有正确编码并且 pdf 文件没有正确解析。
小问题
有谁知道如何使用 node/cypress 命令使用 PDF 数据的响应流创建 pdf 文件。我试过 Axios 插件、http、xmlhttprequest 插件。
【问题讨论】:
-
你的问题没有很好地表达,请提供更多关于它不能始终如一地工作的详细信息。这太模糊了,无法调试。
-
@RichardMatsen:我已经更新了描述。如果您想了解更多详细信息,请告诉我。我还没有弄清楚解决方案
-
谢谢,好多了。你试过pdf-parse吗,下载量很大。
-
抛出 fs 对象的控制台...你试过cy.readFile()而不是
fs吗? -
是的,我已经安装 pdf-parse 并尝试过。但是pdf解析使用“require('fs')。并且Fs不起作用。抛出控制台错误。通过互联网上的快速搜索,我发现“你不能在浏览器中使用fs”。是的,cy.readFile => I用过,但同样的问题。
标签: typescript automated-tests typescript-typings cypress