我想测试一个用 react-modal 构建的组件。该库使用门户将实际模态安装在父级之外。酶中的查找方法仅查看从包装器元素开始的树,不包括开放模式。
据我所知,直到最近,门户网站还没有得到官方支持,但从 React 16 和 Enzyme 3 开始,它们应该是 ( enzyme-252 )
看起来开放门户可以从 DOM 中通过安装有酶的组件访问,但要找到它并不容易。我已经看到使用 refs 的策略(我宁愿不添加它只是为了测试)和 document.querySelector (比处理 ReactWrapper 更糟糕)。
最有希望的策略声称可以使用foundEl.node.portal(react-modal-563 )从它的父级访问门户,但我还没有让它工作(似乎节点属性可能已被弃用,因为当我使用它时,我得到一个错误:
Attempted to access ReactWrapper::node, which was previously a private property on
Enzyme ReactWrapper instances, but is no longer and should not be relied upon.
Consider using the getElement() method instead.
有没有人找到更好的策略或让这个策略起作用?我在 Enzyme 3.1.1、React Enzyme Adapter 1.0.4 和 React 16.2 上供参考。
const wrapper = mount(
<div>
<Provider store={store}>
<MyModal isOpen={true} />
</Provider>
</div>
);
console.log('modal node', wrapper.find(ReactModal).node) // error
console.log('modal element', wrapper.find(ReactModal).getElement(0)) // ReactModal element with props, etc, but no portal
console.log('from query', document.querySelector(`.ReactModalPortal`)) // Finds it, but I would rather not do it this way