React测试库和onAnimationEnd

9

假设有一个带有一些CSS动画(例如滑入/滑出)的组件:

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

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

有没有一种方法可以模拟这个过程?

1个回答

11
你可以使用 fireEvent.animationEnd() 函数在 div 元素上触发 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');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接