使用Jest-dom如何检测ModalVideo组件打开状态下是否应用指定样式
问题解决方案
常见报错原因
- 传入
toHaveStyle的样式字符串包含多余的换行、缩进空白符,无法和元素实际样式匹配 - 待校验的样式未应用在
data-testid="modalVideo"绑定的元素上,而是作用在组件内部的子容器 - 模态框打开存在过渡动画,初始渲染时样式尚未完全挂载就执行了断言
- 若项目使用CSS-in-JS方案,部分编译后的样式优先级/属性写法和测试传入的不匹配
修复步骤
步骤1:替换样式校验写法
优先使用对象格式传入toHaveStyle,避免字符串格式的空白符干扰,属性采用CSS驼峰命名:
// 替换原有的字符串写法,对象格式稳定性更高 expect(getByTestId('modalVideo')).toHaveStyle({ position: 'fixed', display: 'flex' })
步骤2:确认元素绑定正确性
打开浏览器控制台检查组件渲染后的DOM结构,确认position: fixed、display: flex两个样式确实是加在data-testid="modalVideo"对应的元素上;如果样式是加在内部子容器上,需要给对应子元素新增data-testid属性后再查询校验。
步骤3:处理动画过渡场景
如果模态框打开有动画延迟,使用waitFor包裹断言等待样式生效:
import React from 'react'; import { render, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import TestThemeProvider, { defaultTheme, } from '../../../providers/themeProvider/testThemeProvider'; import ModalVideo from '.'; describe('ModalVideo', () => { test('ModalVideo has correct styles when is full screen', async () => { const { getByTestId } = render( <TestThemeProvider> <ModalVideo data-testid="modalVideo" isOpen={true} videoURL={'https://player.vimeo.com/external/the-url'} callToAction={'Play video'} ></ModalVideo> </TestThemeProvider> ); await waitFor(() => { expect(getByTestId('modalVideo')).toHaveStyle({ position: 'fixed', display: 'flex' }) }) }); });
可选优化
如果你使用的是@testing-library/react v13及以上版本,cleanup会在每个测试用例后自动执行,可删除手动声明的afterEach(cleanup)代码。
内容的提问来源于stack exchange,提问作者Toni Michel Caubet
相关产品推荐
相关产品推荐

