Testing the useDebouncedUndo Hook

We are going to use the waitForNextUpdate function to test debouncing in our useDebouncedUndo Hook by following these steps:

  1. Create a new src/hooks/useDebouncedUndo.test.js file.
  2. Import the renderHook and act functions as well as the useDebouncedUndo Hook:
import { renderHook, act } from '@testing-library/react-hooks'
import useDebouncedUndo from './useDebouncedUndo'
  1. First of all, we test whether the Hook returns a proper result, including the content value, setter function, and the undoRest object:
test('should use debounced undo', () => {
const { result } = renderHook(() => useDebouncedUndo())
const [ content, setter, undoRest ] = result.current

expect(content).toBe('')
expect(typeof setter).toBe('function')
expect(typeof undoRest.undo).toBe('function')
expect(typeof undoRest.redo).toBe('function')
expect(undoRest.canUndo).toBe(false)
expect(undoRest.canRedo).toBe(false)
})

  1. Next, we test whether the content value gets updated immediately:
test('should update content immediately', () => {
const { result } = renderHook(() => useDebouncedUndo())
const [ content, setter ] = result.current

expect(content).toBe('')
act(() => setter('test'))
const [ newContent ] = result.current
expect(newContent).toBe('test')
})
Remember that we can give any name to variables we pull out from an array using destructuring. In this case, we first name the content variable as content, then, later, we name it newContent.
  1. Finally, we use waitForNextUpdate to wait for the debounced effect to trigger. After debouncing, we should now be able to undo our change:
test('should debounce undo history update', async () => {
const { result, waitForNextUpdate } = renderHook(() => useDebouncedUndo())
const [ , setter ] = result.current

act(() => setter('test'))

const [ , , undoRest ] = result.current
expect(undoRest.canUndo).toBe(false)

await act(async () => await waitForNextUpdate())

const [ , , newUndoRest ] = result.current
expect(newUndoRest.canUndo).toBe(true)
})

As we can see, we can use async/await in combination with the waitForNextUpdate function to easily handle testing asynchronous operations in our Hooks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.196.184