testing - 如何使用 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 吗?
提前致谢。
解决方案
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" }
推荐阅读
- r - 带有连接平均线的 geom_boxplot 的自定义图例
- javascript - ajax函数没有被触发
- angular-cli - 无法安装角度
- c# - Xamarin.Essentials“无法检测到当前 Activity。确保您已在 Activity 或 Application 类中调用了 Init。”
- python - python中带有特殊字符的字符串实习
- android - AsyncTask 没有执行多次
- c - 不使用结构的多项式数相加
- mysql - prestashop 数据库大容量表 ps_search_index
- runtime-error - 在 python 3.7 中学习二分搜索
- c# - 使用 DataContractJsonSerializer 将元素附加到文件中的 JSON 数组