Similarly to how we tested the useUserState Hook, we can also test the usePostsState Hook.
Let's test the usePostsState Hook now:
- Create a new src/hooks/usePostsState.test.js file.
- 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'
- 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([])
})
- 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)
})
- 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.