码迷,mamicode.com
首页 > 其他好文 > 详细

[React Testing] Mock react-transition-group in React Component Tests with jest.mock

时间:2020-05-01 01:32:17      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:wait   ansi   text   hello   ext   completed   ati   out   extra   

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 { render, fireEvent } from @testing-library/react
import { HiddenMessage } from ../extra/hidden-message

jest.mock(‘react-transition-group‘, {
  CssTransition: (props) => {
    return props.in ? props.children : null
  },
})

test(show hidden message when toggle is clicked, () => {
  const message = Hello World
  const { getByText, queryByText } = render(
    <HiddenMessage>{message}</HiddenMessage>,
  )
  const button = getByText(/toggle/i)
  expect(queryByText(message)).not.toBeInTheDocument()
  fireEvent.click(button)
  expect(queryByText(message)).toBeInTheDocument()
  fireEvent.click(button)
  expect(queryByText(message)).not.toBeInTheDocument()
})

 

[React Testing] Mock react-transition-group in React Component Tests with jest.mock

标签:wait   ansi   text   hello   ext   completed   ati   out   extra   

原文地址:https://www.cnblogs.com/Answer1215/p/12812256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!