Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test content of iFrame using jest

I want to test content of the iFrame Tag using jest.

For e.g I have a small html file that shows google homepage in iframe.

I want to test that google homepage is coming in iFrame or not.

<!DOCTYPE html>
<html>
   <body>
   <h2>Google</h2>
      <iframe src="http://www.google.com" style="border:none;"></iframe>
   </body>
</html>

can someone suggest me that how can I test that iframe using jest ?

Thanks in Advance.

like image 673
Jaydeep Bobade Avatar asked Nov 13 '18 06:11

Jaydeep Bobade


1 Answers

const fs = require('fs');
const path = require('path');
const html = fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf8'); //--> get the file content


describe('Iframe Test Suit', function () {
    beforeEach(() => {
        document.body.innerHTML = html.toString(); 
    });


    it('Should load iframe content', function (done) {
      const iframe = document.querySelector("iframe"); //--> get the iframe element
      expect(iframe).toBeTruthy();
      
      onLoad();

      function onLoad() {
         const iframeContent = iframe.contentDocument || iframe.contentWindow.document;
         if (iframeContent.readyState == "complete") { 
            const input = iframeContent.querySelector("input");
            expect(input).toBeTruthy();
            done();
         } else {
           setTimeout(() => onLoad(), 100); //--> call again if iframe content is not loaded
         }
       }
    });
});
  

By default, jsdom will not load any sub-resources like iframes. To load such resources you can pass the resources: "usable" option, which will load all usable resources.

jest.config.js

"testEnvironmentOptions": { "resources": "usable" }
like image 106
lissettdm Avatar answered Nov 09 '22 03:11

lissettdm