zoukankan      html  css  js  c++  java
  • [React Testing] Test your Custom Hook Module with react-hooks-testing-library

    It's always important to test your code, especially if you're open-sourcing it for others to use. In this video, we'll learn how to use react-hooks-testing-library to write a few tests for our custom hook.

    import { useState, useEffect } from 'react'
    
    export function useStarWarsQuote() {
      const [quote, setQuote] = useState('')
      const [loading, setLoading] = useState(false)
    
      useEffect(() => {
        async function getStarWarsQuote() {
          setLoading(true)
          // Get initial text
          const response = await fetch(
            'https://starwars-quote-proxy-gi0d3x1lz.now.sh/api/randomQuote'
          )
          const data = await response.json()
          const quote = data.starWarsQuote
          setQuote(quote)
          setLoading(false)
        }
        getStarWarsQuote()
      }, [])
    
      return { quote, loading }
    }

    Test:

    import { renderHook } from '@testing-library/react-hooks'
    import { useStarWarsQuote } from './'
    
    describe('useStarWarsQuote', () => {
      test('should return an object with the keys: loading, quote', () => {
        // result.current = the value returned by our hook
        const { result } = renderHook(() => useStarWarsQuote())
    
        expect(result.current).toHaveProperty('loading')
        expect(result.current).toHaveProperty('quote')
      })
    
      test('should set loading to true after initial call', () => {
        const { result } = renderHook(() => useStarWarsQuote())
        expect(result.current.loading).toBe(true)
      })
    
      test('should return a quote and set loading to false', async () => {
        // Add test here
        const { result, waitForNextUpdate } = renderHook(() => useStarWarsQuote())
    
    
        await waitForNextUpdate()
        expect(typeof result.current.quote).toBe('string')
        expect(result.current.quote).not.toBe(null)
        expect(result.current.quote).not.toBe('')
        expect(result.current.loading).toBe(false)
      })
    })
  • 相关阅读:
    白盒测试相关内容总结
    黑盒测试相关内容总结
    int.parse的出错异常处理
    逃的过初一逃不过十五之三个输入框文本内容检测的实现及测试
    EditBox问题等价类划分
    关于课堂上Exercise#1的讨论
    js中关于事件处理函数名后面是否带括号的问题
    关于提升和作用域的一道有趣的题目
    绝对定位对元素宽度的影响
    js异步函数队列
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12827669.html
Copyright © 2011-2022 走看看