hooks-test-util
make React hooks unit test easier to write
Install
// use yarnyarn add hooks-test-util -D// use npmnpm install hooks-test-util --dev
Doc
render
-
render(callback, options) => { container, unmount, rerender }
: render method to mount a component which include your custom hook -
container
: same asreact-testing-library
container, addhook
field on it, every time visit hook instance should usecontainer.hook
!!! -
unmount()
: method to unmount component -
rerender(options)
: method to rerender component
callback
() => hook instance
: return your custom hook
Options
render({ hook }) : ReactNode
: render method to render dom to hook componentparent : React.ComponentType
: parent component, usually used for context test
Demo
useState Test
hook
const textHook = { const state setState = return text: statetext { } }
test file
useContext Test
hook
const ThemeContext = React const testHook = { const value = return value}
test file
import render act from 'hooks-test-util'
demo:
https://github.com/ariesjia/hooks-test-util/blob/master/src/tests/context.test.tsx
useEffect Test
demo:
https://github.com/ariesjia/hooks-test-util/blob/master/src/tests/effort.test.tsx
test with dom
test file
import render act from '../index'import getByTestId from 'react-testing-library'