Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created October 31, 2023 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustafadalga/475769fcb77b08a813bf5dae0a145027 to your computer and use it in GitHub Desktop.
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
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);
});
})
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