[React Testing] Test your Custom Hook Module with react-hooks-testing-library
React with module your test library hook Testing
2023-09-14 09:00:47 时间
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 使用hooks
- React组件继承,泛型写法
- [React Testing] Test your Custom Hook Module with react-hooks-testing-library
- [React ARIA Testing] Test Accessibility of Rendered React Components with jest-axe
- [React] as component prop
- [React] Improve developer experience for accessing context with a custom React hook
- [PWA] Access the Camera in a PWA built with React
- [PWA] Cache JSON Data in a React PWA with Workbox, and Display it while Offline
- [React] Call setState with null to Avoid Triggering an Update in React 16
- [React] Style a React component with styled-components
- [React] Linting React JSX with ESLint (in ES6)
- React组件继承,泛型写法
- [React ARIA Testing] Test Accessibility of Rendered React Components with jest-axe
- [React] Avoiding state flickers
- [React] Extend styles with styled-components in React
- [React] Test friendly approach
- [React Flow] Up and Running with Facebook Flow for Typed JavaScript
- [React Testing] className with Shallow Rendering
- [React] Intro to inline styles in React components
- 如何得到React应用转换后的JavaScript代码
- Atitit React的相关概念东东 attilax总结
- React.memo() 和 useMemo() 的用法是什么,有哪些区别?
- 【taro react】---- 兼容微信小程序和H5的海报绘制插件