You need to enable JavaScript to run this app. 使用Jest与Testing Library触发fireEvent时如何正确测试图片上传onload校验逻辑
优惠活动
大模型
产品
解决方案
定价
更多

使用Jest与Testing Library触发fireEvent时如何正确测试图片上传onload校验逻辑

图片宽高比校验测试Promise不Resolve的解决方案

现有代码实现

宽高比校验函数

export default function checkAspectRatio(value) {
  return new Promise(resolve => {
    let reader = new FileReader();
    reader.readAsDataURL(value);
    reader.onload = function(value) {
      let img = new Image();
      img.src = value.target.result;
      img.onload = function() {
        const aspectRatio = this.width / this.height;
        resolve(aspectRatio);
      };
    };
  });
}

上传回调逻辑

在file类型input的onChange事件中调用校验函数,为File对象挂载宽高比属性:

// ...
Object.defineProperty(file, 'aspectRatio', {
  value: await checkAspectRatio(file)
});
// ...

测试用例

it('should choose file and validate the file', async () => {
    //...
    const inputFile = getByLabelText('input-button-upload');
    const mockImage = new File(['png'], 'test.png', {
      type: 'image/png',
    });
    fireEvent.change(inputFile, {
        target: {
        files: [mockImage]
        }
    });
    expect(await inputFile.files[0]).toBe(mockImage);
    expect(getByText('test.png')).toBeInTheDocument();
});

问题根因

  • 测试环境(jsdom)不具备真实图片解码能力,构造的mockFile仅包含字符串png,不是合法的二进制图片数据,Image对象加载时会直接触发onerror,永远不会执行onload回调。
  • 原checkAspectRatio函数没有任何错误捕获逻辑,FileReader读取错误、Image加载错误都不会触发Promise的reject,导致Promise永久pending无法resolve。
  • 测试没有等待异步校验流程完成就直接断言渲染内容,时序不匹配;原测试中await inputFile.files[0]为冗余逻辑,files属性是同步可访问的。

调整方案

第一步:优化校验函数健壮性

给函数补充错误捕获和reject逻辑,避免Promise永久挂起,同时修正原代码中回调参数命名混淆的问题:

export default function checkAspectRatio(value) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    // 捕获文件读取错误
    reader.onerror = () => reject(new Error('文件读取失败'));
    reader.readAsDataURL(value);
    reader.onload = function(e) {
      const img = new Image();
      // 捕获图片加载错误
      img.onerror = () => reject(new Error('图片加载失败'));
      img.src = e.target.result;
      img.onload = function() {
        const aspectRatio = this.width / this.height;
        resolve(aspectRatio);
      };
    };
  });
}

第二步:调整测试逻辑

方案1:Mock浏览器原生API适配jsdom环境

如果需要完整覆盖上传流程,可在测试文件中全局mockFileReader和Image的行为,模拟真实加载流程:

// 测试文件顶部添加
global.FileReader = class {
  readAsDataURL() {
    // 直接触发onload返回mock的data url
    this.onload({ target: { result: 'mock-image-data-url' } });
  }
};
global.Image = class {
  set src() {
    // 模拟图片加载完成自动触发onload
    this.onload();
  }
  // 模拟固定图片宽高
  get width() { return 16; }
  get height() { return 9; }
};

修改测试用例,使用waitFor等待异步校验流程完成后再断言:

import { waitFor } from '@testing-library/react';
it('should choose file and validate the file', async () => {
    const inputFile = getByLabelText('input-button-upload');
    const mockImage = new File(['fake-png-binary'], 'test.png', {
      type: 'image/png',
    });
    fireEvent.change(inputFile, {
        target: { files: [mockImage] }
    });
    // 等待所有异步流程完成后再执行断言
    await waitFor(() => {
      expect(inputFile.files[0]).toBe(mockImage);
      expect(getByText('test.png')).toBeInTheDocument();
    });
});

方案2:直接Mock校验函数

如果不需要在测试中验证checkAspectRatio本身的逻辑,可直接mock该函数的返回值,跳过浏览器原生API依赖:

// 测试文件顶部添加
jest.mock('./checkAspectRatio', () => {
  return jest.fn().mockResolvedValue(16/9);
});

后续测试用例的断言逻辑与方案1一致,使用waitFor等待异步流程完成即可。

内容的提问来源于stack exchange,提问作者wizzone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 13:45:10