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

Jest中使用next/image报错:res.cloudinary.com未在next.config.js配置

解决方法按优先级依次尝试:

  • 重启开发服务
    next.config.js的修改不会触发热更新,修改配置后需要完全停止当前运行的npm run dev/yarn dev命令,重新启动服务后配置才会生效。
  • 适配高版本Next.js的配置规则
    如果你使用的是Next.js 13及以上版本,images.domains配置项已被废弃,需要替换为remotePatterns写法,配置示例如下:
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const withPWA = require('next-pwa')
    const isProd = process.env.NODE_ENV === 'production'
    
    module.exports = withPWA({
      pwa: {
        dest: 'public',
        disable: !isProd
      },
      images: {
        remotePatterns: [
          {
            protocol: 'https',
            hostname: 'res.cloudinary.com',
            pathname: '**'
          },
          {
            protocol: 'http',
            hostname: 'localhost',
            pathname: '**'
          }
        ]
      }
    })
    
  • 处理测试环境的特殊情况
    从报错栈可以判断该错误是单元测试运行时触发的,测试环境默认不会加载next.config.js的配置,你可以在测试全局配置文件中mock next/image组件规避该问题,示例如下:
    // jest.setup.js 或对应的测试初始化文件
    jest.mock('next/image', () => ({
      __esModule: true,
      default: (props) => <img {...props} alt={props.alt} />
    }))
    
  • 检查配置文件格式
    删除你当前next.config.js中module.exports前面的多余缩进,避免配置解析异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:45:07