zoukankan      html  css  js  c++  java
  • [React Testing] Mock react-transition-group in React Component Tests with jest.mock

    There are some situations where you want to focus your tests on a particular component and not any of its children. There are other situations where you want to mock out the behavior of components that your component renders. In the case of react-transition-group, we don’t want to have to wait until the transition has completed before we can go on with our tests. Let’s see how we can mock the implementation of react-transition-group using jest.mock to make our tests more reliable and easier to write and maintain.

    Component:

    import React from 'react'
    import { CSSTransition } from 'react-transition-group'
    
    function Fade(props) {
      return (
        <CSSTransition unmountOnExit timeout={1000} classNames="fade" {...props} />
      )
    }
    
    function HiddenMessage({ children }) {
      const [show, setShow] = React.useState(false)
      const toggle = () => setShow((s) => !s)
      return (
        <div>
          <button onClick={toggle}>Toggle</button>
          <Fade in={show}>
            <div>{children}</div>
          </Fade>
        </div>
      )
    }
    
    export { HiddenMessage }

    Test:

    import React from 'react'
    import { render, fireEvent } from '@testing-library/react'
    import { HiddenMessage } from '../extra/hidden-message'
    import '@testing-library/jest-dom/extend-expect'
    
    jest.mock('react-transition-group', () => {
      return {
        CSSTransition: (props) => (props.in ? props.children : null),
      }
    })
    
    test('shows hidden message when toggle is clicked', () => {
      const myMessage = 'hello world'
      const { getByText, queryByText } = render(
        <HiddenMessage>{myMessage}</HiddenMessage>,
      )
      const toggleButton = getByText(/toggle/i)
      expect(queryByText(myMessage)).not.toBeInTheDocument()
      fireEvent.click(toggleButton)
      expect(getByText(myMessage)).toBeInTheDocument()
      fireEvent.click(toggleButton)
      expect(queryByText(myMessage)).not.toBeInTheDocument()
    })
  • 相关阅读:
    Spring和Mybatis整合
    Spring的基本操作
    mybatis在xml文件中处理特殊符号(如:大于号小于号等的方法)
    配置MyBatis 环境
    iframe元素內嵌页面如何去掉继承的html及body背景色/背景图片
    如何解决include包含页面的乱码问题
    Servlet重定向后,页面混乱的解决办法
    使用Ajax验证邮箱是否存在
    使用监听器监听用户访问页面的次数
    基于arduino的红外传感系统
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12812256.html
Copyright © 2011-2022 走看看