首页 > 解决方案 > React:使用 react-measure 的测试组件

问题描述

我正在尝试测试一个使用 react-measure 的组件。

组件非常简单

class AdjustableIframe extends React.Component {
  props: {
    children: node
  };

  render () {
    return (
      <Measure
        bounds
        onResize={(contentRect) => {
          console.log("I want to handle resize")
        }
        }
      >
        {({ measureRef }) => (
          <div ref={measureRef}>
            { this.props.children }
          </div>
        )
        }
      </Measure>
    )
  }
}

我正在尝试为这个组件编写一个测试(因为我想对 onResize 方法有一个复杂的逻辑)。但我不知道如何在我的 Jest 测试中模拟调整大小。

我试图调用 window.resizeTo 但这没有帮助。

谁能设法使它工作?

标签: reactjsjestjsmeasure

解决方案


你应该能够做这样的事情:

const windowSize = 500;

Object.assign(window, {
  innerWidth: windowSize,
  innerHeight: windowSize,
  outerWidth: windowSize,
  outerHeight: windowSize,
}).dispatchEvent(new Event('resize'));

这对我react-media有用,希望它对你也有用!


推荐阅读