如何在测试中模拟Stencil组件的文件上传?
问题解决:Stencil组件测试中模拟文件上传的Fetch报错问题
核心问题原因
- 测试环境(如JSDOM)未启动HTTP服务器,直接用
fetch("./example.pdf")发起相对路径请求会触发InvalidURLException—— 本地文件无法通过HTTP协议被fetch访问。 - 直接给
input.value赋值Blob/File对象无效,文件输入框的files属性必须通过DataTransfer对象模拟设置。
解决方案一:模拟File对象(无需真实文件内容)
如果仅需验证文件上传流程,不需要真实PDF内容,可以直接构造测试用的File对象:
it('should import the file', async () => { // 构造模拟PDF文件 const testFile = new File(['dummy pdf content'], 'example.pdf', { type: 'application/pdf' }); // 获取组件内的文件输入框 const input = host.shadowRoot.querySelector('input[type="file"]'); // 用DataTransfer模拟文件选择操作 const dataTransfer = new DataTransfer(); dataTransfer.items.add(testFile); input.files = dataTransfer.files; // 触发input事件,触发组件的importFile逻辑 input.dispatchEvent(new Event('input')); // 在这里添加你的断言逻辑,比如验证组件是否正确处理了上传文件 });
解决方案二:读取真实本地PDF文件(需要真实内容)
如果必须使用项目中的example.pdf真实内容,可通过Node.js的fs模块读取文件,再转换为File对象:
import * as fs from 'fs'; import * as path from 'path'; it('should import the real PDF file', async () => { // 生成文件的绝对路径(根据你的文件实际位置调整路径) const filePath = path.resolve(__dirname, './example.pdf'); // 读取文件内容并转换为File对象 const fileBuffer = fs.readFileSync(filePath); const testFile = new File([fileBuffer], 'example.pdf', { type: 'application/pdf' }); // 获取输入框并模拟文件上传 const input = host.shadowRoot.querySelector('input[type="file"]'); const dataTransfer = new DataTransfer(); dataTransfer.items.add(testFile); input.files = dataTransfer.files; input.dispatchEvent(new Event('input')); // 添加断言逻辑 });
内容的提问来源于stack exchange,提问作者Carla Candiotti
相关产品推荐
相关产品推荐

