要测试 useEffect
钩子根据 prop
更改 CSS 属性,可以使用测试工具库(如 react-testing-library
或 enzyme
)和断言库(如 jest
)来编写测试代码。以下是一个示例:
import React, { useEffect } from 'react';
import { render } from '@testing-library/react';
function MyComponent({ prop }) {
useEffect(() => {
if (prop) {
document.body.style.backgroundColor = 'red';
} else {
document.body.style.backgroundColor = 'blue';
}
}, [prop]);
return <div>My Component</div>;
}
describe('MyComponent', () => {
afterEach(() => {
document.body.style.backgroundColor = ''; // 清除测试过程中更改的样式
});
it('should change the background color to red when prop is true', () => {
const { rerender } = render(<MyComponent prop={false} />);
expect(document.body.style.backgroundColor).toBe('blue');
rerender(<MyComponent prop={true} />);
expect(document.body.style.backgroundColor).toBe('red');
});
it('should change the background color to blue when prop is false', () => {
const { rerender } = render(<MyComponent prop={true} />);
expect(document.body.style.backgroundColor).toBe('red');
rerender(<MyComponent prop={false} />);
expect(document.body.style.backgroundColor).toBe('blue');
});
});
在这个示例中,我们创建了一个简单的组件 MyComponent
,它接受一个 prop
。当 prop
为真时,背景颜色应为红色;当 prop
为假时,背景颜色应为蓝色。在 useEffect
钩子中,我们使用 prop
的值来更改文档的背景颜色。
测试代码中,我们使用 render
方法来渲染组件,并使用断言来验证背景颜色的改变是否符合预期。通过使用 rerender
方法,我们可以在组件重新渲染时更新 prop
的值并重新执行 useEffect
钩子。
在每个测试用例之后,我们使用 afterEach
钩子来清除测试过程中更改的样式,以确保测试的独立性。