vadim
vadim

Reputation: 43

How to mock in JEST document html elements like webview or iframe?

I'm trying to write some unit tests with Jest for a React component that renders an <webview>. Electron's webview tag is based on Chromium's webview which is some sort of an iframe.

Everytime I run my tests I get into an error when the code riches an event listener method. Here is my code bellow:

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

My test error is: TypeError: Cannot read property 'addEventListener' of undefined.

  it('should render without crashing', () => {
    shallow(
      <TestComponent iframeError={false} />
    );
  });

How do I mock such kind of behaviors in jest?

Upvotes: 0

Views: 2488

Answers (1)

vadim
vadim

Reputation: 43

Since no one posted an answer, I will do so. Cause I found a way to do it. So it's possible in jest to mock on the global object like so:

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

Let me know if you may see some improvements or other ways to deal with it. Thanks

Upvotes: 1

Related Questions