0

我在反应应用程序中使用视频反应。我必须测试一个从视频反应组件调用 ref 方法的组件。我希望使用酶,这样我就可以挂载组件并检查我是否在 ComponentDidMount 中调用了 ref 方法。

基本上,我如何测试 refs.player.seek 是否像下面那样被调用?

componentDidMount() {
    this.refs.player.seek(this.props.currentTime);
    this.refs.player.subscribeToStateChange(this.handlePlayerStateChange);
}
4

1 回答 1

1

由于video-react需要 refs 来调用 play、pause 和 seek 据我所知,我最终使用了这种模式,所以我可以模拟我自己的 ref 回调命中渲染方法。

https://medium.com/@planttheidea/never-render-in-react-testing-again-fc4bcfc2f71d

示例组件代码:

export const createComponentWillReceiveProps = instance => ({seekTime, isPlaying, onSeekComplete}) => {
  const {paused} = instance.playerRef.getState().player;

  if (seekTime) {
    instance.playerRef.seek(seekTime);
    onSeekComplete();
  }
  if (isPlaying && paused) {
    instance.playerRef.play();
  }
  if (!isPlaying && !paused) {
    instance.playerRef.pause();
  }
};

...

componentWillReceiveProps = createComponentWillReceiveProps(this)

...

<VideoReactPlayer ref={el => this.playerRef = el} preload='auto' src={source}>

...

测试看起来像这样:

  it('calls playerRef.play when isPlaying prop is true & paused is true', () => {
    const instance = {playerRef: {play: jest.fn(), getState: () => ({player: {paused: true}})}};
    const componentWillReceiveProps = createComponentWillReceiveProps(instance);
    componentWillReceiveProps({isPlaying: true});
    expect(instance.playerRef.play).toBeCalled();
  });
于 2017-09-06T19:04:32.887 回答