本文背景是运行在 node.js 的 React 组件单元测试。
比如断言元素的宽高?
答案:使用 window.getComputedStyle(el)。
假设我们封装了一个三个点的动画 loading 组件,允许用自定义尺寸和 gap,现在想对其做单元测试。
结构如下:
示例代码:
<div style={{ display: 'flex', alignItems: 'center' }}>
自定义间距和大小 40px 间距 20px:
<LoadingDots
dotStyle={{ width: '40px', height: '40px' }}
gap={20}
/>
</div>
单测:
// 1. 获取父元素
const customized = screen.getByText('自定义间距和大小 40px 间距 20px:').querySelector('div')!
// 2. 获取所有的 dot
const customizedDots = customized.querySelectorAll('span')
// 3. 断言存在 3 个点
expect(customizedDots).toHaveLength(3)
// 使用 getComputedStyle 断言设置的 **gap** 符合预期
expect(window.getComputedStyle(customized).gap).toBe('20px')
// 使用 getComputedStyle 断言设置的**宽高**符合预期
customizedDots.forEach((dot) => {
expect(window.getComputedStyle(dot).width).toBe('40px')
expect(window.getComputedStyle(dot).height).toBe('40px')
})
注意
getComputedStyle只适合通过 inline style 设置的值,如果通过 css class 则不能。- 不能使用
el.getBoundingRect(),无论是通过 style 还是 css class。