Testing the usePostsState Hook

Similarly to how we tested the useUserState Hook, we can also test the usePostsState Hook.

Let's test the usePostsState Hook now:

  1. Create a new src/hooks/usePostsState.test.js file.
  2. Import the necessary functions, the useDispatch and usePostsState Hooks, and the StateContextWrapper:
import { renderHook, act } from '@testing-library/react-hooks'
import { StateContextWrapper } from './testUtils'
import useDispatch from './useDispatch'
import usePostsState from './usePostsState'
  1. Then, we test the initial state of the posts array:
test('should use posts state', () => {
const { result } = renderHook(
() => usePostsState(),
{ wrapper: StateContextWrapper }
)

expect(result.current).toEqual([])
})
  1. Next, we test whether a FETCH_POSTS action replaces the current posts array:
test('should update posts state on fetch action', () => {
const { result } = renderHook(
() => ({ state: usePostsState(), dispatch: useDispatch() }),
{ wrapper: StateContextWrapper }
)

const samplePosts = [{ id: 'test' }, { id: 'test2' }]
act(() => result.current.dispatch({ type: 'FETCH_POSTS', posts: samplePosts }))
expect(result.current.state).toEqual(samplePosts)
})
  1. Finally, we test whether a new post gets inserted on a CREATE_POST action:
test('should update posts state on insert action', () => {
const { result } = renderHook(
() => ({ state: usePostsState(), dispatch: useDispatch() }),
{ wrapper: StateContextWrapper }
)

const post = { title: 'Hello World', content: 'This is a test', author: 'Test User' }
act(() => result.current.dispatch({ type: 'CREATE_POST', ...post }))
expect(result.current.state[0]).toEqual(post)
})

As we can see, the tests for the posts state are similar to the user state, but with different actions being dispatched.

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

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