Skip to content

panjiesw/react-hooks-testing-library

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

76 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

react-hooks-testing-library

ram

Simple component wrapper and utilities for testing React hooks.


Build Status codecov version downloads MIT License

All Contributors PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

The problem

You're writing an awesome custom hook and you want to test it, but as soon as you call it you see the following error:

Invariant Violation: Hooks can only be called inside the body of a function component.

You don't really want to write a component solely for testing this hook and have to work out how you were going to trigger all the various ways the hook can be updated, especially given the complexities of how you've wired the whole thing together.

The solution

The react-hooks-testing-library is built on top of the wonderful react-testing-library to create a simple test harness for React hooks that handles running them within the body of a function component, as well as providing various useful utility functions for updating the inputs and retrieving the outputs of your amazing custom hook.

Using this library, you do not have to concern yourself with how to construct, render or interact with the react component in order to test your hook. You can just use the hook directly and assert the results.

When to use this library

  1. You're writing a library with one or more custom hooks that are not directly tied a component
  2. You have a complex hook that is difficult to test through component interactions

When not to use this library

  1. Your hook is defined along side a component and is only used there
  2. Your hook is easy to test by just testing the components using it

Example

// useCounter.js
import { useState } from 'react'

function useCounter(initialCount = 0) {
  const [count, setCount] = useState(initialCount)

  const incrementBy = useCallback((n) => setCount(count + n), [count])
  const decrementBy = useCallback((n) => setCount(count - n), [count])

  return { count, incrementBy, decrementBy }
}

export default useCounter
// useCounter.test.js
import { renderHook, cleanup, act } from 'react-hooks-testing-library'
import useCounter from './useCounter'

afterEach(cleanup)

test('should create counter', () => {
  const { result } = renderHook(() => useCounter())

  expect(result.current.count).toBe(0)
})

test('should increment counter', () => {
  const { result } = renderHook(() => useCounter())

  act(() => result.current.incrementBy(1))

  expect(result.current.count).toBe(1)

  act(() => result.current.incrementBy(2))

  expect(result.current.count).toBe(3)
})

test('should decrement counter', () => {
  const { result } = renderHook(() => useCounter())

  act(() => result.current.decrementBy(1))

  expect(result.current.count).toBe(-1)

  act(() => result.current.decrementBy(2))

  expect(result.current.count).toBe(-3)
})

Installation

npm install --save-dev react-hooks-testing-library

API

renderHook(callback[, options])

Renders a test component that will call the provided callback, including any hooks it calls, every time it renders.

Note: testHook has been renamed to renderHook. testHook will continue work in the current version with a deprecation warning, but will be removed in a future version.

You should update any usages of testHook to use renderHook instead.

Arguments

  • callback (function()) - function to call each render. This function should call one or more hooks for testing.
  • options (object) - accepts the same options as react-testing-library's render function, as well as:
    • initialProps (object) - the initial values to pass to the callback function

Returns

  • result (object)
    • current (any) - the return value of the callback function
  • waitForNextUpdate (function) - returns a Promise that resolves the next time the hook renders, commonly when state is updated as the result of a asynchronous action.
  • rerender (function([newProps])) - function to rerender the test component including any hooks called in the callback function. If newProps are passed, the will replace the initialProps passed the the callback function for future renders.
  • unmount (function()) - function to unmount the test component, commonly used to trigger cleanup effects for useEffect hooks.

cleanup()

Unmounts any React trees that were mounted with renderHook.

This is the same cleanup function that is exported by react-testing-library.

act(callback)

This is the same act function that is exported by react-testing-library.

Contributors

Thanks goes to these wonderful people (emoji key):

Michael Peyper
Michael Peyper

πŸ’» 🎨 πŸ“– πŸ€” πŸš‡ πŸ“¦ ⚠️ πŸ”§
otofu-square
otofu-square

πŸ’»
Patrick P. Henley
Patrick P. Henley

πŸ€” πŸ‘€

This project follows the all-contributors specification. Contributions of any kind welcome!

Issues

Looking to contribute? Look for the Good First Issue label.

πŸ› Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

πŸ’‘ Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a πŸ‘. This helps maintainers prioritize what to work on.

See Feature Requests

❓ Questions

For questions related to using the library, you can raise issue here, or visit a support community:

LICENSE

MIT

About

Simple component wrapper for testing React hooks

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 87.2%
  • TypeScript 12.8%