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

Jest 26.x中assetTransformer配置异常,快照未返回图片路径

Jest 资源转换器返回process方法而非图片路径,断言失败

我使用jest@26.6.3配置了资源转换器处理图片等静态资源,期望测试时能返回图片的相对路径,但实际输出的是转换器的process函数,导致断言不通过。

我的资源转换器代码(assetsTransformer.js)

const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    const relativePath = path.relative(config.rootDir, filename);
    return `module.exports = ${JSON.stringify({testUri: relativePath})};`;
  },
};

jest.config.js 配置

moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetsTransformer.js",         
},

测试失败输出

Object {
-   "testUri": "../../../src/assets/images/uncheck2.png",
+   "process": [Function process],
  }

  309 |         const imgTick = getByTestId('imgTick');
  310 |
> 311 |         expect(imgTick.props.source).toEqual({ testUri: '../../../src/assets/images/uncheck2.png' });
      |                                      ^
  312 |     })
  313 | });
  314 |

解决方法

问题出在配置项的选择上:moduleNameMapper仅做模块路径映射,不会执行转换器的process方法,所以直接导出了转换器对象。正确应该用transform配置来指定资源转换器。

修改jest.config.js:

module.exports = {
  // 保留其他原有配置
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy"
  },
  transform: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetsTransformer.js"
  }
};

这样Jest会调用转换器的process方法处理对应类型的文件,返回你期望的包含testUri的对象,断言就能正常通过了。

额外检查点:

  • 确认assetsTransformer.js的路径正确,<rootDir>指向项目根目录
  • 确保Jest配置文件被正确加载(比如放在根目录命名为jest.config.js)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:20:16