zoukankan      html  css  js  c++  java
  • [React Testing] Test timer related feature in React

    Sometimes your react component may need to do some cleanup work in the return value from useEffect or useLayoutEffect, or the componentWillUnmount lifecycle method for class components. Luckily for us, as far as React Testing Library is concerned, whichever of those you use is an implementation detail, so your test looks exactly the same regardless of how you implement it. Check out how you can test that simply with React Testing Library and a <Countdown />component.

    Component:

    import React from 'react'
    
    function Countdown() {
      const [remainingTime, setRemainingTime] = React.useState(10000)
      const end = React.useRef(new Date().getTime() + remainingTime)
      React.useEffect(() => {
        const interval = setInterval(() => {
          const newRemainingTime = end.current - new Date().getTime()
          if (newRemainingTime <= 0) {
            clearInterval(interval)
            setRemainingTime(0)
          } else {
            setRemainingTime(newRemainingTime)
          }
        })
        return () => clearInterval(interval)
      }, [])
      return remainingTime
    }
    
    export { Countdown }

    Testing:

    import React from 'react'
    import { render, act } from '@testing-library/react'
    import { Countdown } from '../extra/countdown'
    
    beforeAll(() => {
      jest.spyOn(console, 'error').mockImplementation(() => {})
    })
    
    afterAll(() => {
      console.error.mockRestore()
    })
    
    afterEach(() => {
      jest.clearAllMocks()
      jest.useRealTimers()
    })
    
    test('does not attempt to set state when unmounted (to prevent memory leaks)', () => {
      jest.useFakeTimers() // similar to fakeAsync
      const { unmount } = render(<Countdown />)
      unmount()
      // act is similar to Angualr flush
      act(() => jest.runOnlyPendingTimers())
      expect(console.error).not.toHaveBeenCalled()
    })
  • 相关阅读:
    [day002]剑指 Offer 09. 用两个栈实现队列
    [day003]718. 最长重复子数组
    [linux]关于Ubuntu中Could not get lock /var/lib/dpkg/lock解决方案
    96. 不同的二叉搜索树
    91. 解码方法
    [动态规划]64. 最小路径和
    62.不同路径
    【Java】list根据某一条件进行分组
    【Java】批量生成小程序参数码并打包下载
    【Docker】使用docker制作libreoffice镜像并解决中文乱码问题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12825014.html
Copyright © 2011-2022 走看看