How do I use testing-library to fire React’s animationEnd event with a value for animationName?

I have a React + TypeScript project where I want to use Jest and testing-library to confirm that a div element is removed from the DOM after a CSS animation completes. However, the removal must only happen after an animation with the name “fadeOut” is completed.

The code below is a simplified and contrived example. I only want the div to be removed when an animation with the name “fadeOut” is completed.

The problem is that jest’s JSDOM headless browser doesn’t fire css animation events. I need to fire them manually. And it seems that I can’t pass the animationName property along with the event to my component. A console.log of the animationName always indicates that the animationName is undefined in jest, but correct in the browser.

Here is the SASS file Example.module.scss

@keyframes fadeIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

Here is the Example.tsx component React code:

import React, { useCallback, useState } from 'react';
import s from './Example.module.scss';

const Example = () => {
  const [isMounted, setIsMounted] = useState<boolean>(true);
  const [isFading, setIsFading] = useState<boolean>(false);

  const handleOnAnimationEnd = useCallback(
    (ev: React.AnimationEvent<HTMLDivElement>) => {
      console.log(`The animationName is : "${ev.animationName}"`);
      if (ev.animationName === s.fadeOut) {
        console.log('finished fading out.');
        setIsMounted(false);
      }
      if (ev.animationName === s.fadeIn) {
        console.log('finished fading in.');
      }
    },
    []
  );

  const handleOnClick = useCallback(() => {
    if (isMounted) {
      setIsFading(true);
    }
  }, [isMounted]);

  return (
    <>
      <h1>Contrived example for Stack Overflow:</h1>
      <button onClick={handleOnClick}>Toggle</button>
      {(isMounted || isFading) && (
        <div
          data-testid="div"
          style={{
            animation: `${isFading ? s.fadeOut : s.fadeIn} 400ms forwards`,
          }}
          onAnimationEnd={handleOnAnimationEnd}
        >
          Hello!
        </div>
      )}
    </>
  );
};

export default Example;

Here is my Example.test.tsx test file:

import React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Example from './Example';

describe('Example', () => {
  it('should fade out', async () => {
    expect.hasAssertions();
    const user = userEvent.setup();
    render(<Example />);
    const divEl = screen.getByTestId('div');
    const buttonEl = screen.getByRole('button');
    user.click(buttonEl);

    // jsdom doesn't fire animation events
    fireEvent.animationStart(divEl);

    // manually fire animationEnd event because jsdom doesn't.
    fireEvent.animationEnd(divEl, { animationName: 'fadeOut' });

    await waitFor(() => {
      expect(screen.queryByTestId('div')).not.toBeInTheDocument();
    });
  });
});

And this is the CLI output from running my test:

console.log
    The animationName is : "undefined"

      at lib/Example/Example.tsx:10:15

 FAIL  lib/Example/Example.test.tsx
  Example
    ✕ should fade out (1064 ms)

  ● Example › should fade out

    expect(element).not.toBeInTheDocument()

    expected document not to contain element, found <div data-testid="div" style="animation: fadeOut 400ms forwards;">Hello!</div> instead

    Ignored nodes: comments, script, style
    <html>
      <head />
      <body>
        <div>
          <h1>
            Contrived example for Stack Overflow:
          </h1>
          <button>
            Toggle
          </button>
          <div
            data-testid="div"
            style="animation: fadeOut 400ms forwards;"
          >
            Hello!
          </div>
        </div>
      </body>
    </html>

      20 |
      21 |     await waitFor(() => {
    > 22 |       expect(screen.queryByTestId('div')).not.toBeInTheDocument();
         |                                               ^
      23 |     });
      24 |   });
      25 | });

      at lib/Example/Example.test.tsx:22:47
      at runWithExpensiveErrorDiagnosticsDisabled (../../node_modules/@testing-library/dom/dist/config.js:47:12)
      at checkCallback (../../node_modules/@testing-library/dom/dist/wait-for.js:124:77)
      at checkRealTimersCallback (../../node_modules/@testing-library/dom/dist/wait-for.js:118:16)
      at Timeout.task [as _onTimeout] (../../node_modules/jsdom/lib/jsdom/browser/Window.js:520:19)

As you can see in the output, the onAnimationEnd callback function is called, but the animationName property is undefined. You can also see that the animation did switch to fadeOut from fadeIn, so the correct animation is getting applied.

If I take out the check for the animationName, it works. But in this contrived example, I really need to be able to reference the animationName. It is a requirement for my actual code in my real project.

How does one pass the animationName property along with the event using testing-library’s fireEvent.animationEnd() method?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật