javascript - 如何在 JEST 文档中模拟 webview 或 iframe 等 html 元素?
问题描述
我正在尝试使用 Jest 为呈现<webview>
. Electron 的 webview 标签基于 Chromium 的 webview,它是某种 iframe。
每次我运行测试时,当代码丰富了事件侦听器方法时,我都会遇到错误。下面是我的代码:
const TestComponent = (source, iframeError) => {
const webviewTag = document.querySelector('webview');
webviewTag.addEventListener('plugin-crashed', (name, version) => {
console.log(`plugin-crashed: ${name}, ${version}`);
});
return (
<div className="content-body">
{iframeError
? <IframeError />
: <webivew
id="webview"
name="webivew"
src={source}
autosize
allowpopups
{...optionalAttributes}
plugins
/>
}
</div>
);
};
我的测试错误是:TypeError: Cannot read property 'addEventListener' of undefined
.
it('should render without crashing', () => {
shallow(
<TestComponent iframeError={false} />
);
});
我如何开玩笑地嘲笑这种行为?
解决方案
由于没有人发布答案,我会这样做。因为我找到了一种方法。因此可以像这样jest
模拟global
对象:
beforeEach(() => {
jest.resetModules();
global.document = {
querySelector: function querySelector() {
return webviewTag = {
addEventListener: jest.fn(),
};
}
};
});
让我知道您是否会看到一些改进或其他方法来处理它。谢谢
推荐阅读
- sql-server - XML 路径/资料组合中的对象名称无效
- mysql - 选择所有出现多次的行 - 在同一天
- android - 将 Android Studio 项目添加到新的 git 存储库
- javascript - 预期有一个匹配条件的请求
- amazon-web-services - S3 - 撤销拥有对象的“full_control”权限
- r - SLES12.3上的离线r-base安装
- vb.net - 用鼠标点击和键盘UP和DOWN VB.NET选择listview的项目
- python - 我试图在 django 中获取登录用户的对象?此列表是在登录用户的 form.save 时创建的
- python - Tkinter 从菜单栏中多选
- python - 在为每组添加缺失小时数时无法从重复轴重新索引