【问题标题】:How to mock video pause function using JEST?如何使用 JEST 模拟视频暂停功能?
【发布时间】:2019-01-20 14:18:55
【问题描述】:

在我的组件中,我有这样的代码:

this.videoRef.current.pause();

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

当 Is 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(),
    });

不适合我。

【问题讨论】:

    标签: reactjs testing jestjs


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2018-01-18
      • 2021-11-01
      • 2019-08-28
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多