React Testing Library中Button组件样式Props不生效问题求助
问题分析与解决
核心问题
你犯了两个关键错误:
- 定位错误元素:
render返回的container是包裹整个测试组件的根div,并非你设置了红色背景的Button元素,所以它的背景色为空,导致断言失败。 - 颜色格式不匹配:即使定位到正确元素,
window.getComputedStyle返回的颜色值是RGB格式(如rgb(255, 0, 0)),而非你预期的字符串"red"。
修正后的测试代码
import { render, screen } from '../../testUtils/rtl'; import { Button } from '@chakra-ui/react'; describe('Button', () => { it('sample test style props button', () => { render(<Button backgroundColor={'red'}> sample red box</Button>); // 定位到实际的Button元素 const redButton = screen.getByRole('button', { name: /sample red box/i }); // 现在log的URL会指向正确的按钮元素 screen.logTestingPlaygroundURL(); // 方式1:用toHaveStyle断言(更简洁,无需处理RGB格式) expect(redButton).toHaveStyle('background-color: red'); // 方式2:用getComputedStyle断言(需匹配RGB格式) // const buttonStyle = window.getComputedStyle(redButton); // expect(buttonStyle.backgroundColor).toBe('rgb(255, 0, 0)'); }); });
关于你的配置
你的customRender配置没有问题:已经正确用ChakraProvider包裹了组件,并且传入了自定义主题,样式会正常应用到Chakra组件上,无需额外修改。
内容的提问来源于stack exchange,提问作者kelsky
相关产品推荐
相关产品推荐

