Skip to content
Myr

immer.test.tsx

This file

Path

tests/immer.test.tsx

74 lines · 2.2 KiB · TypeScript

Last changed by

test(middleware/immer): add runtime tests for immer middleware (#3471)palkimbefore adoption95d3f33

History of this file

Take it

test(middleware/immer): add runtime tests for immer middleware (#3471)palkimbefore adoption95d3f33

lines 1–74why, one step back
1import { describe, expect, it } from 'vitest'
2import { create } from 'zustand'3import { immer } from 'zustand/middleware/immer'4import { createStore } from 'zustand/vanilla'56describe('immer middleware', () => {7 it('should mutate state via an immer draft (function updater)', () => {8 type State = { count: number; inc: () => void }9 const useBoundStore = create<State>()(10 immer((set) => ({11 count: 0,12 inc: () =>13 set((state) => {14 state.count += 115 }),16 })),17 )1819 useBoundStore.getState().inc()20 expect(useBoundStore.getState().count).toBe(1)21 })2223 it('should not apply produce when updater is not a function', () => {24 type State = { count: number; name: string }25 const useBoundStore = create<State>()(26 immer(() => ({ count: 0, name: 'zustand' })),27 )2829 useBoundStore.setState({ count: 5 })30 expect(useBoundStore.getState()).toEqual({ count: 5, name: 'zustand' })31 })3233 it('should replace the entire state when replace flag is true', () => {34 type State = { a: number; b?: number }35 const useBoundStore = create<State>()(immer(() => ({ a: 1, b: 2 })))3637 useBoundStore.setState({ a: 9 }, true)38 expect(useBoundStore.getState()).toEqual({ a: 9 })39 })4041 it('should produce nested state updates via a draft without mutating the previous state', () => {42 type State = {43 user: { name: string; tags: string[] }44 addTag: (tag: string) => void45 }46 const useBoundStore = create<State>()(47 immer((set) => ({48 user: { name: 'bear', tags: ['a'] },49 addTag: (tag) =>50 set((state) => {51 state.user.tags.push(tag)52 }),53 })),54 )5556 const previousUser = useBoundStore.getState().user57 useBoundStore.getState().addTag('b')5859 expect(useBoundStore.getState().user.tags).toEqual(['a', 'b'])60 expect(useBoundStore.getState().user).not.toBe(previousUser)61 expect(previousUser.tags).toEqual(['a'])62 })6364 it('should work with vanilla createStore', () => {65 type State = { count: number }66 const store = createStore<State>()(immer(() => ({ count: 0 })))6768 store.setState((state) => {69 state.count = 1070 })7172 expect(store.getState().count).toBe(10)73 })74})