用酶测试反应模态 - 无法找到门户网站

时间:2018-01-19 18:18:58

标签: javascript reactjs enzyme react-modal

我想测试一个用react-modal构建的组件。该库使用门户将实际模式安装在父项之外。酶中的find方法只能看到从你的包装元素开始的树,它不包括open模式。

据我所知,直到最近,门户网站才得到官方支持,但从React 16和Enzyme 3开始,它们应该是(Python 3.5.4 documentation

看起来开放式门户网站可以通过酶装组件在DOM中访问,但要找到它并不容易。我已经看过使用refs的策略(我不想仅仅为测试添加)和document.querySelector(比处理ReactWrapper更糟糕)。

最有希望的策略声称门户网站可以使用foundEl.node.portal(enzyme-252从其父级访问,但我没有得到这个工作(似乎可能已经弃用了node属性,因为当我用它,我收到一个错误: 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

1 个答案:

答案 0 :(得分:0)

ReactDOM.createPortal = jest.fn(modal => modal)