繁体   English   中英

如何使用 React 测试库测试 React 门户内部的模式?

[英]How can I test a modal inside of a React Portal using React Testing Library?

我正在尝试使用 React 测试库测试我的Modal组件。 Modal 在 React Portal 中呈现。 现在,当我尝试将我的Modal与快照匹配时,快照将呈现为空 div。

test('The component should render in body when open', () => {
    const {container} = render(
        <Modal>
            <div>My dialog content</div>
        </Modal>
    );

    expect(container).toMatchSnapshot();
});

我得到的快照是这样的:

exports[`The component should render in body when open 1`] = `<div />`;

我见过一些解决方法,例如将{container: document.body}作为第二个参数传递给render() function。但没有任何效果。

我也无法通过container查询任何元素。 它总是返回null

const dialog = container.querySelector(".modal");
console.log(dialog); // null

我最终通过快照baseElement而不是container使其工作 两者都是由render() function 返回的属性。

test('The component should render in body when open', () => {
    const {baseElement} = render(
        <Modal>
            <div>My dialog content</div>
        </Modal>
    );

    expect(baseElement).toMatchSnapshot();
});

首先,您应该确定门户的容器元素,即添加到正文中以保存门户内容的“根”节点。 然后你应该在 DOM 中手动附加/添加它,以便你的渲染方法知道在哪里渲染你的模态组件。 然后您应该使用 baseElement 属性而不是容器,因为门户元素在主体内呈现,然后根据快照测试您的 baseElement(这是实际的门户元素)的 firstChild。

这对我有用:

it('should render', () => {
  document.body.innerHTML = '<div id="my-root-element-id" />';
    
  const { baseElement } = render(<Default />);
    
  expect(baseElement.firstChild).toMatchSnapshot();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM