How to mock video duration in react testing library?

Viewed 1136

How to mock video duration from fire event loadedMetadata with react-testing library?

in my React code, I'm retrieving the video duration with loadedMetaData event listener:

const MyVideo = () => {
   const [videoDuration, setVideoDuration] = useState(0);

   const handleMetadataLoaded = e => {
      setVideoDuration(e.currentTarget.duration);
   }

   return (
      <video
         data-testid="vidMyVideo"
         src="*some_source*"
         poster="*poster_image*"
         onLoadedMetadata={handleMetadataLoaded}
      />

   );

}

and I try to make a unit test for the code above:

import '@testing-library/jest-dom/extend-expect';
import { act, fireEvent, render } from '@testing-library/react';

...

const MyVideo = require('../').default;
const { findByTestId } = render(
   <MyVideo />
);
const inlineVideo = await findByTestId('vidMyVideo');
// the event is fired but I got NaN for the duration. how to mock it?
await act(async () => fireEvent.loadedMetadata(inlineVideo));

the loadedMetadata is fired but I got NaN for the duration. How can I mock the video duration?

1 Answers

you can modify the jsdom object

Object.defineProperty(inlineVideo, 'duration', {
   writable: true,
   value: 10,
});
Related