Created
October 31, 2023 18:03
-
-
Save mustafadalga/475769fcb77b08a813bf5dae0a145027 to your computer and use it in GitHub Desktop.
Writing unit tests of zustand state management store with vitest and testing-library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { act, renderHook } from '@testing-library/react'; | |
import { describe, it, expect, beforeEach } from "vitest"; | |
import { usePostsStore } from "@/_store/usePostsStore"; | |
describe('usePostsStore', () => { | |
beforeEach(() => { | |
usePostsStore.getState().reset() | |
}); | |
it('should return the initial state', () => { | |
const { result } = renderHook(() => usePostsStore()); | |
expect(result.current.posts).toEqual([]); | |
}); | |
it('should update the post status when setPosts is called', () => { | |
const posts = [ | |
{ | |
"userId": 1, | |
"id": 1, | |
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", | |
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" | |
} | |
] | |
const { result } = renderHook(() => usePostsStore()); | |
expect(result.current.posts).toEqual([]); | |
act(() => result.current.setPosts(posts)); | |
expect(result.current.posts).toEqual(posts); | |
}); | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { create, StoreApi } from 'zustand'; | |
import { devtools } from "zustand/middleware"; | |
export interface Post { | |
userId: number; | |
id: number; | |
title: string; | |
body: string; | |
} | |
export interface State { | |
posts: Post[], | |
} | |
export interface Actions { | |
setPosts: (posts: Post[]) => void; | |
reset: () => void | |
} | |
const initialState: State = { | |
posts: [] | |
} | |
const createState = (set: StoreApi<State & Actions>["setState"]): State & Actions => ({ | |
...initialState, | |
setPosts: (posts) => set(({ posts })), | |
reset: () => set(initialState) | |
}); | |
export const usePostsStore = create(devtools(createState)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment