Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock video pause function using JEST?

In my components I have code like this:

this.videoRef.current.pause();

Where videoRef is <video ref={this.videoRef} autoPlay muted > ...

When Is pause reached in test, I am getting a error:

 Error: Not implemented: HTMLMediaElement.prototype.pause

How can I mock pause function?

    const wrapper = mount(<ComponentWithVideoTag />);

    const el = wrapper.find('video').props();
    Object.defineProperty(el, 'paused', {
        writable: true,
        value: jest.fn(),
    });

Not working for me.

like image 784
hiacliok Avatar asked Aug 13 '18 19:08

hiacliok


1 Answers

I wouldn't worry about trying to mock the props on the specific element, just mock the higher-level API that is being called. You can achieve this with spyOn, just be sure to call mockRestore on the stub afterwards (just in case you need it elsewhere in the file).

const pauseStub = jest
  .spyOn(window.HTMLMediaElement.prototype, 'pause')
  .mockImplementation(() => {})
const wrapper = mount(<ComponentWithVideoTag />);
// trigger the code that you would expect to call the pause function
expect(pauseStub).toHaveBeenCalled()
pauseStub.mockRestore()
like image 131
Mitch Lillie Avatar answered Oct 13 '22 04:10

Mitch Lillie