[React Testing] Test your Custom Hook Module with react-hooks-testing-library
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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) }) })
以上是关于[React Testing] Test your Custom Hook Module with react-hooks-testing-library的主要内容,如果未能解决你的问题,请参考以下文章
[React Testing] Test componentDidCatch handler Error Boundaries
[React Testing] Improve Test Confidence with the User Event Module
[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段
在 react-testing-library 中,渲染应该只调用一次吗?