3

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.

Vijay P R
  • 1,162
  • 1
  • 10
  • 16

1 Answers1

2

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;
  });
};
Vijay P R
  • 1,162
  • 1
  • 10
  • 16