Check the contents of the <iframe> in the React component with the enzyme

I wrote a simple React component that displays an <iframe> :

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

and I try to check it by checking that the content loaded with src is correctly filled in the <iframe> . To do this, I try to access frame.contentWindow , but after installing it with Enzyme, it always returns undefined .

I tried to make fun of the contents of the <iframe> using Sinon FakeXMLHttpRequest :

 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 <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 for an enzyme test:

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

The component works and displays as expected in the browser with a valid src attribute. Is there a way to access contentWindow in React tests with Enzyme (or any other test environment)?

+7
javascript reactjs iframe sinon enzyme
source share
1 answer

If you write unit test (and I assume that this is what you are doing), you should check the behavior, not the implementation details.

If I had to write a test for such a component, I would use smth:

  • positive scenario: the component displays an iframe with src passed
  • negative scenario: the component displays zero (depending on business logic) if src not passed in the details

This test handles both correct and incorrect behavior. See Defensive Programming for more information.

If we are talking about implementing a test, I would use the Jest method and toMatchSnapshot to check the rendering result in both scenarios.

-one
source share

All Articles