【发布时间】:2017-05-17 19:13:22
【问题描述】:
我编写了一个简单的 React 组件,它呈现一个 <iframe>:
export class Iframe extends React.component {
render() {
return <iframe src={ this.props.src } />;
}
}
我尝试通过检查以src 加载的内容是否在<iframe> 中正确填充来测试它。
为此,我尝试访问 frame.contentWindow,但在使用 Enzyme 安装它后,它总是返回 undefined。
我尝试用诗乃FakeXMLHttpRequest模拟<iframe>内容:
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' />);
和<iframe src='data:text/html' >:
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