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

Jest测试:如何匹配HTML类型的children入参?

解决方案

方案1:匹配单个React元素(最精准)

如果你的children是单个JSX节点(HTML形式的React元素),可以用expect.any(React.ReactElement),记得先导入React:

import React from 'react';

const defaultProps = {
  title: "Foo",
  contentLoaded: true,
  type: 'center', // 注意这里如果是字符串常量要加引号
  passedFunc: expect.any(Function),
  id: "id-1234",
  children: expect.any(React.ReactElement)
};

方案2:匹配任意非空值(最宽松)

如果只需要确认children属性存在且不为null/undefined,不管它的具体类型(文本、元素数组等都能匹配),用expect.anything()即可:

const defaultProps = {
  // ...其他属性
  children: expect.anything()
};

方案3:匹配任意对象(兼容元素/数组)

React元素和元素数组本质都是对象类型,用expect.any(Object)也能满足匹配需求:

const defaultProps = {
  // ...其他属性
  children: expect.any(Object)
};

额外提示

如果children可能是多个元素组成的数组,且你想确认数组内都是React元素,可以这样写:

children: expect.arrayContaining([expect.any(React.ReactElement)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:50:12