【问题标题】:react-testing-library and onAnimationEndreact-testing-library 和 onAnimationEnd
【发布时间】:2021-06-02 10:47:59
【问题描述】:

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

function MyComponent(props) {
  return (
    <div
      className="with-animations"
      onAnimationEnd={() => {
        // set internal state
        // logic which needs coverage
      }}
    >
      {props.children}
    </div>
  );
}

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

有没有办法模拟出来?

【问题讨论】:

    标签: reactjs css-animations react-testing-library


    【解决方案1】:

    您可以在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');
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-07
      • 2021-08-09
      • 1970-01-01
      • 2021-07-18
      • 2021-02-28
      • 2019-06-14
      • 2020-02-27
      • 2019-05-21
      • 2021-02-11
      相关资源
      最近更新 更多