首页 > 解决方案 > 如何使用 jest 测试 iFrame 的内容

问题描述

我想用 jest 测试 iFrame 标签的内容。

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

我想测试谷歌主页是否进入 iFrame。

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

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

提前致谢。

标签: testingiframejunitjestjstestng

解决方案


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
         }
       }
    });
});
  

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

jest.config.js

"testEnvironmentOptions": { "resources": "usable" }

推荐阅读