hia*_*iok 9 testing reactjs jestjs
在我的组件中,我有这样的代码:
this.videoRef.current.pause();
Run Code Online (Sandbox Code Playgroud)
哪里videoRef
是<video ref={this.videoRef} autoPlay muted > ...
当pause
测试达到了,我得到一个错误:
Error: Not implemented: HTMLMediaElement.prototype.pause
Run Code Online (Sandbox Code Playgroud)
如何模拟暂停功能?
const wrapper = mount(<ComponentWithVideoTag />);
const el = wrapper.find('video').props();
Object.defineProperty(el, 'paused', {
writable: true,
value: jest.fn(),
});
Run Code Online (Sandbox Code Playgroud)
不为我工作。
Mit*_*lie 15
我不会担心尝试模拟特定元素上的道具,只需模拟正在调用的更高级别的 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()
Run Code Online (Sandbox Code Playgroud)