如何使用JEST模拟视频暂停功能?

时间:2018-08-13 19:28:12

标签: reactjs testing jestjs

在我的组件中,我有如下代码:

this.videoRef.current.pause();

videoRef<video ref={this.videoRef} autoPlay muted > ...的地方

在测试中达到pause时,我得到一个错误:

 Error: Not implemented: HTMLMediaElement.prototype.pause

如何模拟暂停功能?

    const wrapper = mount(<ComponentWithVideoTag />);

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

不为我工作。

1 个答案:

答案 0 :(得分:1)

我不会担心尝试模拟特定元素上的道具,而只是模拟正在调用的高级API。您可以使用spyOn实现此目的,只需确保稍后在存根上调用mockRestore(以防万一,您需要在文件的其他位置使用它)。

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()
相关问题