Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock animate function in react-testing-library / jest

I am using animate function to animate height of a div. The code looks like this and happens in useLayoutEffect :

      const animation = ref.current.animate(
        { height: [oldHeight, newHeight] },
        { duration: 100 }
      );

And my component JSX looks like :

 return (
  <div ref={ref}> {children} </div>
)

But during testing with react-testing-library I get the error ref.current.animate is not a function. I confirmed that ref.current is defined. How can we mock this function with Jest . Went through Jest documentation on mocking functions , window object etc but couldn't find info on how to mock these functions on dom nodes.

like image 796
Vijay P R Avatar asked Mar 28 '26 18:03

Vijay P R


1 Answers

Ended up mocking as :



const animationMock = () => {
  type Animate = {
    (
      keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
      options?: number | KeyframeAnimationOptions | undefined
    ): Animation;
    (
      keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
      options?: number | KeyframeAnimationOptions | undefined
    ): Animation;
  };

  let originalAnimateFunction: Animate;

  // Mock native animate function
  beforeAll(() => {
    originalAnimateFunction = HTMLDivElement.prototype.animate;

    const obj = {
      onfinish: () => {},
    };

    const animationFunction = function (this: any) {
      Promise.resolve().then(async () => {
        act(() => obj.onfinish());
      });

      return obj as unknown as Animation;
    };

    HTMLDivElement.prototype.animate = animationFunction;
  });

  afterAll(() => {
    HTMLDivElement.prototype.animate = originalAnimateFunction;
  });
};
like image 108
Vijay P R Avatar answered Mar 31 '26 10:03

Vijay P R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!