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

React组件执行submit后Jest快照返回null,如何解决?

问题出在update()方法的错误使用上

你这里的核心问题是错误调用了login.update()——React Test Renderer的update方法不是用来强制触发组件重新渲染的,它的作用是接收一个新的React元素,用来更新组件的props。你无参数调用update()会导致内部渲染逻辑异常,最终返回null。

接下来分两种场景给你解决方法:

场景1:Login是类组件

如果你的Login是类组件,调用instance.submit()后组件的state已经更新,组件会自动触发重新渲染,根本不需要调用update()。直接获取快照即可:

it('Contains error message when submit with empty fields', () => {
  const login = renderer.create(<Login />)
  const instance = login.getInstance()
  // 触发提交,此时组件state更新并自动重渲染
  instance.submit()
  // 直接生成快照
  expect(login.toJSON()).toMatchSnapshot()
})

场景2:Login是函数组件

如果Login是函数组件,getInstance()会返回null(函数组件没有实例),这时候你不能直接调用submit方法,而是要模拟真实的用户交互来触发提交行为。推荐使用@testing-library/react的工具来做这件事,它更贴近真实用户行为:

import { render, fireEvent } from '@testing-library/react'

it('Contains error message when submit with empty fields', () => {
  const { getByRole, asFragment } = render(<Login />)
  // 找到页面上的提交按钮(根据实际按钮的role或文本调整)
  const submitBtn = getByRole('button', { name: /提交/i })
  // 模拟用户点击按钮
  fireEvent.click(submitBtn)
  // 生成当前组件的快照
  expect(asFragment()).toMatchSnapshot()
})

额外补充:React Test Renderer的update方法正确用法示例,当你需要更新组件props时才用它:

// 比如给Login组件传入新的props
login.update(<Login title="新的登录标题" />)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:33:38