Cypress从PNG扫描二维码报错及无截图扫描方法咨询
问题解答
1. 代码错误原因
你遇到的TypeError: qrcode.scan is not a function是因为**@nuintun/qrcode库的API已更新**,当前版本的Decoder类不再提供scan方法,取而代之的是decode方法,且参数要求与旧版scan不同。原教程代码基于旧版库,需调整适配新版API。
2. 修正后的代码示例
/// <reference types="cypress" /> import { Decoder } from '@nuintun/qrcode' it('decodes QR code from local PNG', () => { cy.fixture('frame.png', 'base64') .then(base64 => { // 创建Image对象加载base64格式的图片 const img = new Image() img.src = `data:image/png;base64,${base64}` // 等待图片加载完成再继续 return new Promise((resolve, reject) => { img.onload = () => resolve(img) img.onerror = reject }) }) .then(img => { // 通过canvas将图片转换为ImageData(新版库要求的输入格式) const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') canvas.width = img.width canvas.height = img.height ctx.drawImage(img, 0, 0) const imageData = ctx.getImageData(0, 0, img.width, img.height) // 使用新版API decode解析二维码 const qrcode = new Decoder() return qrcode.decode(imageData) }) .its('data') .then(cy.log) .should('include', 'cypress.tips') })
3. 无需网站截图的本地二维码扫描方案
完全可以直接读取本地PNG文件解析二维码,无需依赖网站截图,核心步骤如下:
- 用
cy.fixture读取本地PNG的base64编码 - 将base64转换为Image对象并等待加载完成
- 通过canvas把Image转换为新版@nuintun/qrcode要求的ImageData格式
- 调用
Decoder.decode方法解析二维码数据
这套方案直接操作本地文件,不需要和网站交互,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者bazzinga
相关产品推荐
相关产品推荐

