Say I have a listStore.js
like this:
import { create } from 'zustand'
import queryList from '@/service'
const useListStore = () => create((get, set) => ({
list: [],
getList: async () => {
const list = await queryList()
const { updateList } = get()
updateList(list)
}
updateList: list => {
set({
list: list.map(i => i + 1)
})
}
}))
To test this store hook, I create a test file named listStore.test.js
like this:
import useListStore from './useListStore'
import { renderHook, act } from '@testing-library/react'
jest.mock('@/service', () => ({
queryList: jest.fn().mockResolvedValue([1,2,3])
}))
describe('test listStore', () => {
test('test updateList function', () => {
// some codes
})
test('test getList function', () => {
const { result } = renderHook(() => useListStore())
act(() => result.current.getList())
expect(queryList).toHaveBeenCalled()
expect(result.current.list).toEqual([2,3,4])
})
})
When testing getList
function, not only should I test the queryList
has been called, but I also need to test that the list
state has been updated correctly.
The key point is that, before I do an assertion like expect(result.current.list).toEqual([2,3,4])
, I have to make sure that the state update has been done. However, I have no idea how to make sure that. Even when I waitFor
or await
the expect
assertion, the state I get seems to be an old value. The list
state is still []
instead of [2,3,4]
.
6