You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何测试Image组件的source属性?

正确测试React Native Image组件source属性的方法

你遇到的问题核心是:React Native打包本地图片资源时,会将require()导入的图片转换为数字ID,而不是你写的变量名(比如arrowRight),所以测试时比对字符串"arrowRight"自然会失败,返回的数字1就是这个资源的打包ID。

解决步骤:

  1. 在测试文件中导入对应的图片资源
    确保你的测试代码里也导入了和组件中路径一致的图片资源:

    import arrowRight from '../assets/arrow-right.png'; // 路径与组件内保持完全一致
    import arrowDown from '../assets/arrow-down.png';
    
  2. 直接比对资源的打包ID/引用
    组件中使用的arrowRight本身就是打包后的资源ID,测试时直接用导入的资源对象做比对即可:

    it('icon should be arrowRight', () => {
      const wrapper = shallow(<DetailsPageLastPosition bike={bike} buttonVisibility={true} />);
      expect(wrapper.find({ testID: 'image-source' }).props().source).toEqual(arrowRight);
    });
    
    it('icon should switch to arrowDown when buttonVisibility is false', () => {
      const wrapper = shallow(<DetailsPageLastPosition bike={bike} buttonVisibility={false} />);
      expect(wrapper.find({ testID: 'image-source' }).props().source).toEqual(arrowDown);
    });
    

补充说明:

  • 如果使用的是远程图片(通过uri指定),source会是{ uri: '图片地址' }格式的对象,此时测试需要直接比对这个对象。
  • 不要尝试比对字符串形式的变量名,React Native打包后不会保留这个名称,仅会留下数字形式的资源ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:55:40