[英]Test the content of an <iframe> in a React component with Enzyme
I've written a simple React component that renders an <iframe>
: 我写了一个简单的React组件来呈现<iframe>
:
export class Iframe extends React.component {
render() {
return <iframe src={ this.props.src } />;
}
}
and I trying to test it by checking that the content loaded with src
is properly populated within the <iframe>
. 我试图通过检查在<iframe>
正确填充src
加载的内容来测试它。 In order to do so I try to access frame.contentWindow
, but after mounting it with Enzyme it always returns undefined
. 为了做到这一点,我尝试访问frame.contentWindow
,但在使用Enzyme挂载后,它总是返回undefined
。
I've tried to mock the <iframe>
content with Sinon FakeXMLHttpRequest
: 我试图用Sinon 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' />);
and with <iframe src='data:text/html' >
: 并使用<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 } />);
but in both cases on the test with Enzyme: 但在两种情况下用酶测试:
container = mount(<Iframe src='...' />);
container.instance().contentWindow // equals 'undefined'
container.find('iframe').contentWindow // equals 'undefined'
The component works and renders as expected on the browser when provided with a valid src
attribute. 当提供有效的src
属性时,该组件在浏览器上按预期工作和呈现。 Is there any way to access contentWindow
in React tests with Enzyme (or any other test framework)? 有没有办法在使用Enzyme(或任何其他测试框架)的React测试中访问contentWindow
?
The problem is still actual. 问题仍然存在。 And the answer is that jsdom provides contentWindow/contentDocument only for attached iframe, and enzyme by default doesn't attach nodes. 答案是jsdom仅为附加的iframe提供contentWindow / contentDocument,默认情况下,酶不附加节点。 There is option for mount which directs enzyme to attach node: 有指导酶连接节点的mount选项:
el = document.createElement('div');
document.body.appendChild(el);
wrapper = mount(<MyReactNode />, { attachTo: el });
If you're writing a unit test (and I assume that this is what you're doing), you should test the behavior, not the implementation details. 如果您正在编写单元测试(我认为这就是您正在做的事情),您应该测试行为,而不是实现细节。
If I had to write a test for such component I'd use smth like that: 如果我必须为这样的组件编写测试,我会使用这样的smth:
src
积极场景:组件使用传递的src
呈现iframe src
passed in props 否定场景:如果没有在props中传递src
,则组件呈现null(取决于业务逻辑) This test handles both: correct and incorrect behavior. 此测试处理两者:正确和不正确的行为。 See Defensive programming for more details. 有关详细信息,请参阅防御性编程 。
If we're talking about the test implementation, I'd use Jest and toMatchSnapshot
method to check the rendering result on both scenarios. 如果我们谈论测试实现,我将使用Jest和toMatchSnapshot
方法检查两种情况下的渲染结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.