Is there any way i can trigger the onEnded attribute on the video element while testing using jest?

Viewed 900

i've been trying to test this component using jest but I've not been able to find a way around it.


function TestUseStateObject() {
  const [state, setState] = React.useState(true);
  const handleAdd = () => {
    console.log('setting state');
    setState(false)
  }
  console.log('state > ', state);
  if(!state) {
    return (<p>Testing</p>)
  }
  return (
    <video src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" autoPlay controls onEnded={() => handleAdd()} />
  )
}
3 Answers

I finally found the answer after struggling for hours!

Using React testing library:

fireEvent.ended(videoElement);

The long form way to do the same is

const endedEvent = createEvent('ended', element);
fireEvent(element, endedEvent);

(The other answers provided here create an 'onEnded' event, which is not an event type, as the event is actually called 'ended')

Using React testing library:

const onEndedEvent = createEvent('onEnded', element);
fireEvent(element, onEndedEvent);

Answer from Klugjo was almost there, but he missed off that you need to include the element in the createEvent function call. Above is a working example.

Related