首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react-testing库和onAnimationEnd

react-testing库和onAnimationEnd
EN

Stack Overflow用户
提问于 2021-03-04 03:54:44
回答 1查看 673关注 0票数 4

给定一个包含一些CSS动画的组件(例如滑入/滑出):

代码语言:javascript
复制
function MyComponent(props) {
  return (
    <div
      className="with-animations"
      onAnimationEnd={() => {
        // set internal state
        // logic which needs coverage
      }}
    >
      {props.children}
    </div>
  );
}

如何验证onAnimationEnd事件处理程序中的代码已被调用?

有没有办法解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-04 05:25:35

您可以在div元素上使用fireEvent.animationEnd()触发onAnimatedEnd事件。

假设您的组件如下所示:

代码语言:javascript
复制
function MyComponent(props) {
    return (
        <div
            data-testid="animationDiv"
            className="with-animations"
            onAnimationEnd={() => {
                console.log('onAnimationEnd called')
            }}
        >
            {props.children}
        </div>
    );
}

您的测试可能如下所示:

代码语言:javascript
复制
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');
});
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66464014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档