【问题标题】:Test the content of an <iframe> in a React component with Enzyme使用 Enzyme 在 React 组件中测试 <iframe> 的内容
【发布时间】:2017-05-17 19:13:22
【问题描述】:

我编写了一个简单的 React 组件,它呈现一个 &lt;iframe&gt;:

export class Iframe extends React.component {
   render() {
        return <iframe src={ this.props.src } />;
    }
}

我尝试通过检查以src 加载的内容是否在&lt;iframe&gt; 中正确填充来测试它。 为此,我尝试访问 frame.contentWindow,但在使用 Enzyme 安装它后,它总是返回 undefined

我尝试用诗乃FakeXMLHttpRequest模拟&lt;iframe&gt;内容:

server = sinon.fakeServer.create();
server.respondWith('GET', 'test', [200, { 'Content-Type': 'text/html' }, '<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body><div class="myClass">Amazing Unicorn</div></body></html>']);
container = mount(<Iframe src='test' />);

&lt;iframe src='data:text/html' &gt;:

const src = 'data:text/html;charset=utf-8,<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><body><div class="myClass">Amazing Unicorn</div></body></html>';
container = mount(<Iframe src={ src } />);

但在这两种情况下都使用酶进行测试:

container = mount(<Iframe src='...' />);
container.instance().contentWindow // equals 'undefined'
container.find('iframe').contentWindow // equals 'undefined'

当提供有效的src 属性时,组件在浏览器上按预期工作和呈现。有没有办法在 React 测试中使用 Enzyme(或任何其他测试框架)访问 contentWindow

【问题讨论】:

  • 我也遇到同样的问题来测试一下,你找到解决办法了吗?
  • 您必须使用“工作”浏览器设置酶。不知道这是否可能。但是,您为什么要对此进行测试?恕我直言,此测试毫无意义,因为您不会测试代码而是做出反应。我认为您应该只测试道具“src”是否正确传递为 iframe 的“src”属性,这可以通过酶来实现。
  • contentWindow 实际上是 null 而不是未定义,在您 getDOMNode() 并检查属性 contentWindow 之后。您检查的是酶包装器上的属性 contentWindow 而不是 iframe 本身

标签: javascript reactjs iframe sinon enzyme


【解决方案1】:

问题仍然存在。答案是jsdom只为附加的iframe提供contentWindow/contentDocument,而酶默认不附加节点。有一个安装选项可以引导酶附着节点:

el = document.createElement('div');
document.body.appendChild(el);
wrapper = mount(<MyReactNode />, { attachTo: el });

【讨论】:

    【解决方案2】:

    如果您正在编写单元测试(并且我假设这就是您正在做的事情),您应该测试行为,而不是实现细节。

    如果我必须为此类组件编写测试,我会像这样使用:

    • 正面场景:组件渲染一个 iframe 并传递了src
    • 负面场景:如果没有src 传入props,组件将呈现null(取决于业务逻辑)

    此测试同时处理:正确和不正确的行为。详情请见Defensive programming

    如果我们谈论的是测试实现,我会使用JesttoMatchSnapshot 方法来检查两种情况下的渲染结果。

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2017-02-12
      • 2018-08-20
      • 1970-01-01
      • 2020-07-17
      • 2017-01-01
      • 1970-01-01
      • 2019-08-01
      • 2020-11-02
      相关资源
      最近更新 更多