使用PNG库时遇“unrecognised content at end of stream”错误求助
问题排查与解决方案
核心原因
“unrecognised content at end of stream”是pngjs解析PNG文件时抛出的错误,说明读取的文件数据不符合PNG格式规范,常见原因包括:文件读取方式错误导致数据格式不对、下载的文件未完全写入磁盘、文件本身损坏。
具体修复步骤
1. 修正文件读取格式
Cypress的cy.readFile用"binary"模式返回的是字符串,而pngjs需要Buffer类型数据。将读取模式改为null,让Cypress直接返回Buffer:
cy.readFile("cypress/e2e/Testdata/sample.png", null).then((image1) => { cy.readFile("cypress/downloads/sample.png", null).then((image2) => { // 后续解析代码保持不变 }); });
2. 确保下载文件完整写入
Cypress下载操作是异步的,可能出现文件还没写完就开始读取的情况。可以通过文件检查任务确保文件存在且大小合法:
- 先在
cypress.config.js注册文件检查任务:
const fs = require("fs"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on("task", { checkValidFile: (filePath) => { return fs.existsSync(filePath) && fs.statSync(filePath).size > 0; }, }); }, }, });
- 然后在测试代码中等待文件就绪:
cy.readFile("cypress/e2e/Testdata/sample.png", null).then((image1) => { cy.task("checkValidFile", "cypress/downloads/sample.png").then((isValid) => { expect(isValid).to.be.true; cy.readFile("cypress/downloads/sample.png", null).then((image2) => { // 后续解析代码保持不变 }); }); });
3. 验证文件本身有效性
手动打开cypress/downloads/sample.png,确认文件能正常显示。如果文件损坏,检查下载逻辑:比如请求是否返回200状态码、响应内容是否为合法PNG数据。
4. 修正错误的断言逻辑(可选)
原代码中expect(diff.width).to.equal(0)是错误的——diff的宽高和原图片一致,应该断言差异像素数量为0:
// 替换原有的expect语句 const diffPixels = pixelmatch(img1.data, img2.data, null, width, height, { threshold: 0.1 }); expect(diffPixels).to.equal(0);
内容的提问来源于stack exchange,提问作者Srinidhi Reddy Palwai
相关产品推荐
相关产品推荐

