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

Jest如何使用toHaveStyle测试React Native嵌套样式对象shadowOffset

失败原因

你的组件style属性是数组格式,其中包含了有效样式对象和undefined项,旧版React Native Testing Library的toHaveStyle匹配器默认无法自动兼容这种数组嵌套对象的部分匹配场景,因此直接传入嵌套样式对象会断言失败。

解决方案

方案1:使用objectContaining适配嵌套匹配(适配新版测试库)

新版本的测试库已经支持自动打平样式数组,搭配expect.objectContaining做部分匹配即可兼容嵌套对象的校验:

const popover = getByTestId("popover");
expect(popover).toHaveStyle(
  expect.objectContaining({
    shadowOffset: expect.objectContaining({ width: 0, height: 6 })
  })
);

方案2:手动提取样式断言(全版本兼容)

直接从组件props里取出样式数组,过滤掉无效项之后再做断言,写法直观没有版本兼容问题:

const popover = getByTestId("popover");
// 过滤掉样式数组里的undefined项,拿到有效样式对象
const validStyle = popover.props.style.find(Boolean);
// 单独断言shadowOffset
expect(validStyle.shadowOffset).toEqual({ width: 0, height: 6 });

// 同时校验多个样式可以这么写
expect(validStyle).toEqual(expect.objectContaining({
  elevation: 12,
  shadowColor: "#000",
  shadowOffset: { width: 0, height: 6 },
  shadowOpacity: 0.37,
  shadowRadius: 7.49
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:45:05