【问题标题】:How to mock a shadow element in jest testing如何在玩笑测试中模拟阴影元素
【发布时间】:2020-04-28 19:24:30
【问题描述】:

我有一个反应组件ReactComponentContainer,它获取配置和shadowRoot

import React from 'react';
import App from './App';
import ReactComponent from './ReactComponent';

const ReactComponentContainer = function({config, shadowRoot}) {

  configme(shadowRoot.host || shadowRoot);

  return (
    <App renderRoot={shadowRoot}>
      <ReactComponent/>
    </App>
  );
};

export default ReactComponentContainer;

在我的jest 测试文件中,我需要模拟一个shadow dom,所以我可以作为参数传递给ReactComponentContainer。

const header = document.createElement('header');
const shadowRoot = header.attachShadow({mode: 'open'});
shadowRoot.innerHTML = '<h1>Hello Shadow DOM</h1>';
import React from 'react';
import ReactComponentContainer from './ReactComponentContainer';

describe('ReactComponentContainer', () => {
  beforeEach(() => {
    setUp = (props) => {
      return mount(<ReactComponentContainer {...props} />);
    };
  });

  it('initailize ReactComponentContainer', () => {

    // mock a shadow dom
    const header = document.createElement('header');
    // Error: attachShadow is undefined
    const shadowRoot = header.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = '<h1>Hello Shadow DOM</h1>';

    const props = {
      config: {},
      renderRoot: shadowRoot
    };

    const element = setUp(props);
  });
});

我收到Error: attachShadow is undefined。我想是因为它只是浏览器。

我的问题:

如何模拟 shadow dom,以便在开玩笑测试中运行它?

【问题讨论】:

  • 为什么在测试中尝试使用 shadow dom?
  • 无论如何,实现 Shadow API 是 JSDOM 的责任。看起来可能是already supported,只需检查您在package-lock.json中使用的版本(应该是at least 12.2.0

标签: javascript reactjs jestjs shadow-dom jsdom


【解决方案1】:

我使用这篇文章来解决我在 Svelte 中的 shadowRoot 测试问题。 所有函数都放在一个单独的CrudTableService.js中。

要使用 jest 运行单元测试并捕获影子 DOM 以提高代码覆盖率,我找到了这个解决方案:

it('testSetDeleteMode', async () => {
        const documentHTML = '<!doctype html><html><body>' +
            '<crud-table>' +.     // added for shadow DOM test
            '<div id="options-default"></div>' +
            '<div id="options-delete"></div>' +
            '</crud-table>' +     // added for shadow DOM test
            '</body></html>';
        document.body.innerHTML = documentHTML  // for light DOM tests

        // create shadow DOM for customElement
        const crudTable = document.querySelector('crud-table');
        const shadowRoot = crudTable.attachShadow({mode: 'open'});
        shadowRoot.innerHTML = documentHTML;

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2018-09-18
    • 2021-06-16
    • 1970-01-01
    • 2017-11-19
    • 2020-12-06
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多