[英]react-testing-library and onAnimationEnd
Given a component which has some CSS animations (such as sliding in/out):给定一个包含一些 CSS 动画(例如滑入/滑出)的组件:
function MyComponent(props) {
return (
<div
className="with-animations"
onAnimationEnd={() => {
// set internal state
// logic which needs coverage
}}
>
{props.children}
</div>
);
}
How can I verify that the code within the onAnimationEnd
event handler was invoked?如何验证是否调用了onAnimationEnd
事件处理程序中的代码?
Is there a way to mock this out?有没有办法模拟出来?
You can trigger the onAnimatedEnd
event with fireEvent.animationEnd()
on the div
element.您可以在div
元素上使用fireEvent.animationEnd()
触发onAnimatedEnd
事件。
Assuming your component looks like the following:假设您的组件如下所示:
function MyComponent(props) {
return (
<div
data-testid="animationDiv"
className="with-animations"
onAnimationEnd={() => {
console.log('onAnimationEnd called')
}}
>
{props.children}
</div>
);
}
Your test could look like:您的测试可能如下所示:
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.