如何使用玩笑来测试iFrame的内容

Jay*_*ade 5 testing iframe jestjs

我想使用笑话来测试iFrame广告代码的内容。

例如,我有一个小的html文件,该文件在iframe中显示了Google主页。

我想测试一下Google主页是否会出现在iFrame中。

<!DOCTYPE html>
<html>
   <body>
   <h2>Google</h2>
      <iframe src="http://www.google.com" style="border:none;"></iframe>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

有人可以建议我如何使用笑话来测试iframe吗?

提前致谢。

lis*_*tdm 6

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
         }
       }
    });
});
  
Run Code Online (Sandbox Code Playgroud)

默认情况下,jsdom不会加载任何子资源,例如 iframe。要加载此类资源,您可以传递该resources: "usable"选项,这将加载所有可用的资源。

笑话配置.js

"testEnvironmentOptions": { "resources": "usable" }
Run Code Online (Sandbox Code Playgroud)