首页 > 解决方案 > 如何在 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} />
    );
  });

我如何开玩笑地嘲笑这种行为?

标签: javascriptreactjsjestjs

解决方案


由于没有人发布答案,我会这样做。因为我找到了一种方法。因此可以像这样jest模拟global对象:

beforeEach(() => {
  jest.resetModules();
  global.document = {
    querySelector: function querySelector() {
      return webviewTag = {
        addEventListener: jest.fn(),
      };
    }
  };
});

让我知道您是否会看到一些改进或其他方法来处理它。谢谢


推荐阅读