反应测试库和 onAnimationEnd
react-testing-library and onAnimationEnd
给定一个有一些CSS动画的组件(比如滑动in/out):
function MyComponent(props) {
return (
<div
className="with-animations"
onAnimationEnd={() => {
// set internal state
// logic which needs coverage
}}
>
{props.children}
</div>
);
}
如何验证 onAnimationEnd
事件处理程序中的代码已被调用?
有没有办法模拟这个?
您可以在 div
元素上使用 fireEvent.animationEnd()
触发 onAnimatedEnd
事件。
假设您的组件如下所示:
function MyComponent(props) {
return (
<div
data-testid="animationDiv"
className="with-animations"
onAnimationEnd={() => {
console.log('onAnimationEnd called')
}}
>
{props.children}
</div>
);
}
您的测试可能如下所示:
import { fireEvent, render, screen } from '@testing-library/react';
it('test', () => {
const logSpy = jest.spyOn(console, 'log');
render(<MyComponent />);
fireEvent.animationEnd(screen.getByTestId('animationDiv'));
expect(logSpy).toHaveBeenCalledWith('onAnimationEnd called');
});
给定一个有一些CSS动画的组件(比如滑动in/out):
function MyComponent(props) {
return (
<div
className="with-animations"
onAnimationEnd={() => {
// set internal state
// logic which needs coverage
}}
>
{props.children}
</div>
);
}
如何验证 onAnimationEnd
事件处理程序中的代码已被调用?
有没有办法模拟这个?
您可以在 div
元素上使用 fireEvent.animationEnd()
触发 onAnimatedEnd
事件。
假设您的组件如下所示:
function MyComponent(props) {
return (
<div
data-testid="animationDiv"
className="with-animations"
onAnimationEnd={() => {
console.log('onAnimationEnd called')
}}
>
{props.children}
</div>
);
}
您的测试可能如下所示:
import { fireEvent, render, screen } from '@testing-library/react';
it('test', () => {
const logSpy = jest.spyOn(console, 'log');
render(<MyComponent />);
fireEvent.animationEnd(screen.getByTestId('animationDiv'));
expect(logSpy).toHaveBeenCalledWith('onAnimationEnd called');
});