zoukankan      html  css  js  c++  java
  • [React Testing] Test React Portals with within from React Testing Library

    When you use a React Portal, much of your component can be rendered outside the main DOM tree. Let’s see how we can use utilities provided by React Testing Library to allow us to select elements within the portal. To perform actions and assert on what’s rendered.

    Component:

    import React from 'react'
    import ReactDOM from 'react-dom'
    
    let modalRoot = document.getElementById('modal-root')
    if (!modalRoot) {
      modalRoot = document.createElement('div')
      modalRoot.setAttribute('id', 'modal-root')
      document.body.appendChild(modalRoot)
    }
    
    // don't use this for your modals.
    // you need to think about accessibility and styling.
    // Look into: https://ui.reach.tech/dialog
    function Modal({ children }) {
      const el = React.useRef(document.createElement('div'))
      React.useLayoutEffect(() => {
        const currentEl = el.current
        modalRoot.appendChild(currentEl)
        return () => modalRoot.removeChild(currentEl)
      }, [])
      return ReactDOM.createPortal(children, el.current)
    }
    
    export { Modal }

    Testing:

    import React from 'react'
    import { render, within } from '@testing-library/react'
    import { Modal } from '../extra/modal'
    import '@testing-library/jest-dom/extend-expect'
    
    test('modal shows the children', () => {
      render(
        <Modal>
          <div data-testid="test" />
        </Modal>,
      )
    
      // get element only in modal-root
      const { getByTestId } = within(document.getElementById('modal-root'))
      expect(getByTestId('test')).toBeInTheDocument()
    })
  • 相关阅读:
    201215-03-19---cocos2dx内存管理--具体解释
    sqlHelper的增删改查
    Java Web的数据库操作(一)
    Myeclipse 中添加mysql的jdbc驱动
    MySQL索引的创建、删除和查看
    搭建Windows下Java Web开发环境
    Qt 格式化字符串
    实现C++模板类头文件和实现文件分离的方法
    Qt Creator实现状态栏显示
    Win7 64位下配置Qt5.3和Wincap
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12825053.html
Copyright © 2011-2022 走看看