Skip to content
Myr

testing.md

This file

Path

docs/learn/guides/testing.md

741 lines · 20.7 KiB · Markdown

Last changed by

fix(docs): correct react-dom test utils import path (#3474)Aleksei Kharitonovbefore adoption4b96f4e

History of this file

Take it

Show it rendered

1---2title: Testing3description: Writing Tests4nav: 185---67## Setting Up a Test Environment89### Test Runners1011Usually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're12going to be testing UI components, you will likely need to configure the test runner to use JSDOM13to provide a mock DOM environment.1415See these resources for test runner configuration instructions:1617- **Jest**18  - [Jest: Getting Started](https://jestjs.io/docs/getting-started)19  - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)20- **Vitest**21  - [Vitest: Getting Started](https://vitest.dev/guide)22  - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)2324### UI and Network Testing Tools2526**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)27to test out React components that connect to Zustand**. RTL is a simple and complete React DOM28testing utility that encourages good testing practices. It uses ReactDOM's `render` function and29`act` from `react-dom/test-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)30is the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)31family of tools also includes adapters for many other popular frameworks.3233We also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as34this means your application logic does not need to be changed or mocked when writing tests.3536- **React Testing Library (DOM)**37  - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)38  - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)39  - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)40- **Native Testing Library (React Native)**41  - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)42- **User Event Testing Library (DOM)**43  - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)44- **TypeScript for Jest**45  - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)46- **TypeScript for Node**47  - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)48- **Mock Service Worker**49  - [MSW: Installation](https://mswjs.io/docs/getting-started/install)50  - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)51  - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)5253## Setting Up Zustand for testing5455> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using56> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.5758The mock provided below will enable the relevant test runner to reset the zustand stores after each test.5960### Shared code just for testing purposes6162This shared code was added to avoid code duplication in our demo since we use the same counter store63creator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.6465```ts66// shared/counter-store-creator.ts67import { type StateCreator } from 'zustand'6869export type CounterStore = {70  count: number71  inc: () => void72}7374export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({75  count: 1,76  inc: () => set((state) => ({ count: state.count + 1 })),77})78```7980### Jest8182In the next steps we are going to setup our Jest environment in order to mock Zustand.8384```ts85// __mocks__/zustand.ts86import { act } from '@testing-library/react'87import type * as ZustandExportedTypes from 'zustand'88export * from 'zustand'8990const { create: actualCreate, createStore: actualCreateStore } =91  jest.requireActual<typeof ZustandExportedTypes>('zustand')9293// a variable to hold reset functions for all stores declared in the app94export const storeResetFns = new Set<() => void>()9596const createUncurried = <T>(97  stateCreator: ZustandExportedTypes.StateCreator<T>,98) => {99  const store = actualCreate(stateCreator)100  const initialState = store.getInitialState()101  storeResetFns.add(() => {102    store.setState(initialState, true)103  })104  return store105}106107// when creating a store, we get its initial state, create a reset function and add it in the set108export const create = (<T>(109  stateCreator: ZustandExportedTypes.StateCreator<T>,110) => {111  console.log('zustand create mock')112113  // to support curried version of create114  return typeof stateCreator === 'function'115    ? createUncurried(stateCreator)116    : createUncurried117}) as typeof ZustandExportedTypes.create118119const createStoreUncurried = <T>(120  stateCreator: ZustandExportedTypes.StateCreator<T>,121) => {122  const store = actualCreateStore(stateCreator)123  const initialState = store.getInitialState()124  storeResetFns.add(() => {125    store.setState(initialState, true)126  })127  return store128}129130// when creating a store, we get its initial state, create a reset function and add it in the set131export const createStore = (<T>(132  stateCreator: ZustandExportedTypes.StateCreator<T>,133) => {134  console.log('zustand createStore mock')135136  // to support curried version of createStore137  return typeof stateCreator === 'function'138    ? createStoreUncurried(stateCreator)139    : createStoreUncurried140}) as typeof ZustandExportedTypes.createStore141142// reset all stores after each test run143afterEach(() => {144  act(() => {145    storeResetFns.forEach((resetFn) => {146      resetFn()147    })148  })149})150```151152```ts153// setup-jest.ts154import '@testing-library/jest-dom'155```156157```ts158// jest.config.ts159import type { JestConfigWithTsJest } from 'ts-jest'160161const config: JestConfigWithTsJest = {162  preset: 'ts-jest',163  testEnvironment: 'jsdom',164  setupFilesAfterEnv: ['./setup-jest.ts'],165}166167export default config168```169170> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.171172### Vitest173174In the next steps we are going to setup our Vitest environment in order to mock Zustand.175176> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).177> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.178> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`179> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.180> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.181182```ts183// __mocks__/zustand.ts184import { act } from '@testing-library/react'185import type * as ZustandExportedTypes from 'zustand'186export * from 'zustand'187188const { create: actualCreate, createStore: actualCreateStore } =189  await vi.importActual<typeof ZustandExportedTypes>('zustand')190191// a variable to hold reset functions for all stores declared in the app192export const storeResetFns = new Set<() => void>()193194const createUncurried = <T>(195  stateCreator: ZustandExportedTypes.StateCreator<T>,196) => {197  const store = actualCreate(stateCreator)198  const initialState = store.getInitialState()199  storeResetFns.add(() => {200    store.setState(initialState, true)201  })202  return store203}204205// when creating a store, we get its initial state, create a reset function and add it in the set206export const create = (<T>(207  stateCreator: ZustandExportedTypes.StateCreator<T>,208) => {209  console.log('zustand create mock')210211  // to support curried version of create212  return typeof stateCreator === 'function'213    ? createUncurried(stateCreator)214    : createUncurried215}) as typeof ZustandExportedTypes.create216217const createStoreUncurried = <T>(218  stateCreator: ZustandExportedTypes.StateCreator<T>,219) => {220  const store = actualCreateStore(stateCreator)221  const initialState = store.getInitialState()222  storeResetFns.add(() => {223    store.setState(initialState, true)224  })225  return store226}227228// when creating a store, we get its initial state, create a reset function and add it in the set229export const createStore = (<T>(230  stateCreator: ZustandExportedTypes.StateCreator<T>,231) => {232  console.log('zustand createStore mock')233234  // to support curried version of createStore235  return typeof stateCreator === 'function'236    ? createStoreUncurried(stateCreator)237    : createStoreUncurried238}) as typeof ZustandExportedTypes.createStore239240// reset all stores after each test run241afterEach(() => {242  act(() => {243    storeResetFns.forEach((resetFn) => {244      resetFn()245    })246  })247})248```249250> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need251> to add `import { afterEach, vi } from 'vitest'` at the top.252253```ts254// global.d.ts255/// <reference types="vite/client" />256/// <reference types="vitest/globals" />257```258259> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do260> need to remove `/// <reference types="vitest/globals" />`.261262```ts263// setup-vitest.ts264import '@testing-library/jest-dom/vitest'265266vi.mock('zustand') // to make it work like Jest (auto-mocking)267```268269> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need270> to add `import { vi } from 'vitest'` at the top.271272```ts273// vitest.config.ts274import { defineConfig, mergeConfig } from 'vitest/config'275import viteConfig from './vite.config'276277export default defineConfig((configEnv) =>278  mergeConfig(279    viteConfig(configEnv),280    defineConfig({281      test: {282        globals: true,283        environment: 'jsdom',284        setupFiles: ['./setup-vitest.ts'],285      },286    }),287  ),288)289```290291### Testing Components292293In the next examples we are going to use `useCounterStore`294295> **Note**: all of these examples are written using TypeScript.296297```ts298// shared/counter-store-creator.ts299import { type StateCreator } from 'zustand'300301export type CounterStore = {302  count: number303  inc: () => void304}305306export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({307  count: 1,308  inc: () => set((state) => ({ count: state.count + 1 })),309})310```311312```ts313// stores/use-counter-store.ts314import { create } from 'zustand'315316import {317  type CounterStore,318  counterStoreCreator,319} from '../shared/counter-store-creator'320321export const useCounterStore = create<CounterStore>()(counterStoreCreator)322```323324```tsx325// contexts/use-counter-store-context.tsx326import { type ReactNode, createContext, useContext, useState } from 'react'327import { createStore } from 'zustand'328import { useStoreWithEqualityFn } from 'zustand/traditional'329import { shallow } from 'zustand/shallow'330331import {332  type CounterStore,333  counterStoreCreator,334} from '../shared/counter-store-creator'335336export const createCounterStore = () => {337  return createStore<CounterStore>(counterStoreCreator)338}339340export type CounterStoreApi = ReturnType<typeof createCounterStore>341342export const CounterStoreContext = createContext<CounterStoreApi | undefined>(343  undefined,344)345346export interface CounterStoreProviderProps {347  children: ReactNode348}349350export const CounterStoreProvider = ({351  children,352}: CounterStoreProviderProps) => {353  const [store] = useState(() => createCounterStore())354  return (355    <CounterStoreContext.Provider value={store}>356      {children}357    </CounterStoreContext.Provider>358  )359}360361export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T362363export const useCounterStoreContext = <T,>(364  selector: UseCounterStoreContextSelector<T>,365): T => {366  const counterStoreContext = useContext(CounterStoreContext)367368  if (counterStoreContext === undefined) {369    throw new Error(370      'useCounterStoreContext must be used within CounterStoreProvider',371    )372  }373374  return useStoreWithEqualityFn(counterStoreContext, selector, shallow)375}376```377378```tsx379// components/counter/counter.tsx380import { useCounterStore } from '../../stores/use-counter-store'381382export function Counter() {383  const { count, inc } = useCounterStore()384385  return (386    <div>387      <h2>Counter Store</h2>388      <h4>{count}</h4>389      <button onClick={inc}>One Up</button>390    </div>391  )392}393```394395```ts396// components/counter/index.ts397export * from './counter'398```399400```tsx401// components/counter/counter.test.tsx402import { act, render, screen } from '@testing-library/react'403import userEvent from '@testing-library/user-event'404405import { Counter } from './counter'406407describe('Counter', () => {408  test('should render with initial state of 1', async () => {409    renderCounter()410411    expect(await screen.findByText(/^1$/)).toBeInTheDocument()412    expect(413      await screen.findByRole('button', { name: /one up/i }),414    ).toBeInTheDocument()415  })416417  test('should increase count by clicking a button', async () => {418    const user = userEvent.setup()419420    renderCounter()421422    expect(await screen.findByText(/^1$/)).toBeInTheDocument()423424    await user.click(await screen.findByRole('button', { name: /one up/i }))425426    expect(await screen.findByText(/^2$/)).toBeInTheDocument()427  })428})429430const renderCounter = () => {431  return render(<Counter />)432}433```434435```tsx436// components/counter-with-context/counter-with-context.tsx437import {438  CounterStoreProvider,439  useCounterStoreContext,440} from '../../contexts/use-counter-store-context'441442const Counter = () => {443  const { count, inc } = useCounterStoreContext((state) => state)444445  return (446    <div>447      <h2>Counter Store Context</h2>448      <h4>{count}</h4>449      <button onClick={inc}>One Up</button>450    </div>451  )452}453454export const CounterWithContext = () => {455  return (456    <CounterStoreProvider>457      <Counter />458    </CounterStoreProvider>459  )460}461```462463```tsx464// components/counter-with-context/index.ts465export * from './counter-with-context'466```467468```tsx469// components/counter-with-context/counter-with-context.test.tsx470import { act, render, screen } from '@testing-library/react'471import userEvent from '@testing-library/user-event'472473import { CounterWithContext } from './counter-with-context'474475describe('CounterWithContext', () => {476  test('should render with initial state of 1', async () => {477    renderCounterWithContext()478479    expect(await screen.findByText(/^1$/)).toBeInTheDocument()480    expect(481      await screen.findByRole('button', { name: /one up/i }),482    ).toBeInTheDocument()483  })484485  test('should increase count by clicking a button', async () => {486    const user = userEvent.setup()487488    renderCounterWithContext()489490    expect(await screen.findByText(/^1$/)).toBeInTheDocument()491492    await user.click(await screen.findByRole('button', { name: /one up/i }))493494    expect(await screen.findByText(/^2$/)).toBeInTheDocument()495  })496})497498const renderCounterWithContext = () => {499  return render(<CounterWithContext />)500}501```502503> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need504> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.505506### Testing Stores507508In the next examples we are going to use `useCounterStore`509510> **Note**: all of these examples are written using TypeScript.511512```ts513// shared/counter-store-creator.ts514import { type StateCreator } from 'zustand'515516export type CounterStore = {517  count: number518  inc: () => void519}520521export const counterStoreCreator: StateCreator<CounterStore> = (set) => ({522  count: 1,523  inc: () => set((state) => ({ count: state.count + 1 })),524})525```526527```ts528// stores/use-counter-store.ts529import { create } from 'zustand'530531import {532  type CounterStore,533  counterStoreCreator,534} from '../shared/counter-store-creator'535536export const useCounterStore = create<CounterStore>()(counterStoreCreator)537```538539```tsx540// contexts/use-counter-store-context.tsx541import { type ReactNode, createContext, useContext, useState } from 'react'542import { createStore } from 'zustand'543import { useStoreWithEqualityFn } from 'zustand/traditional'544import { shallow } from 'zustand/shallow'545546import {547  type CounterStore,548  counterStoreCreator,549} from '../shared/counter-store-creator'550551export const createCounterStore = () => {552  return createStore<CounterStore>(counterStoreCreator)553}554555export type CounterStoreApi = ReturnType<typeof createCounterStore>556557export const CounterStoreContext = createContext<CounterStoreApi | undefined>(558  undefined,559)560561export interface CounterStoreProviderProps {562  children: ReactNode563}564565export const CounterStoreProvider = ({566  children,567}: CounterStoreProviderProps) => {568  const [store] = useState(() => createCounterStore())569  return (570    <CounterStoreContext.Provider value={store}>571      {children}572    </CounterStoreContext.Provider>573  )574}575576export type UseCounterStoreContextSelector<T> = (store: CounterStore) => T577578export const useCounterStoreContext = <T,>(579  selector: UseCounterStoreContextSelector<T>,580): T => {581  const counterStoreContext = useContext(CounterStoreContext)582583  if (counterStoreContext === undefined) {584    throw new Error(585      'useCounterStoreContext must be used within CounterStoreProvider',586    )587  }588589  return useStoreWithEqualityFn(counterStoreContext, selector, shallow)590}591```592593```tsx594// components/counter/counter.tsx595import { useCounterStore } from '../../stores/use-counter-store'596597export function Counter() {598  const { count, inc } = useCounterStore()599600  return (601    <div>602      <h2>Counter Store</h2>603      <h4>{count}</h4>604      <button onClick={inc}>One Up</button>605    </div>606  )607}608```609610```ts611// components/counter/index.ts612export * from './counter'613```614615```tsx616// components/counter/counter.test.tsx617import { act, render, screen } from '@testing-library/react'618import userEvent from '@testing-library/user-event'619620import { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'621622describe('Counter', () => {623  test('should render with initial state of 1', async () => {624    renderCounter()625626    expect(useCounterStore.getState().count).toBe(1)627  })628629  test('should increase count by clicking a button', async () => {630    const user = userEvent.setup()631632    renderCounter()633634    expect(useCounterStore.getState().count).toBe(1)635636    await user.click(await screen.findByRole('button', { name: /one up/i }))637638    expect(useCounterStore.getState().count).toBe(2)639  })640})641642const renderCounter = () => {643  return render(<Counter />)644}645```646647```tsx648// components/counter-with-context/counter-with-context.tsx649import {650  CounterStoreProvider,651  useCounterStoreContext,652} from '../../contexts/use-counter-store-context'653654const Counter = () => {655  const { count, inc } = useCounterStoreContext((state) => state)656657  return (658    <div>659      <h2>Counter Store Context</h2>660      <h4>{count}</h4>661      <button onClick={inc}>One Up</button>662    </div>663  )664}665666export const CounterWithContext = () => {667  return (668    <CounterStoreProvider>669      <Counter />670    </CounterStoreProvider>671  )672}673```674675```tsx676// components/counter-with-context/index.ts677export * from './counter-with-context'678```679680```tsx681// components/counter-with-context/counter-with-context.test.tsx682import { act, render, screen } from '@testing-library/react'683import userEvent from '@testing-library/user-event'684685import { CounterStoreContext } from '../../../contexts/use-counter-store-context'686import { counterStoreCreator } from '../../../shared/counter-store-creator'687688describe('CounterWithContext', () => {689  test('should render with initial state of 1', async () => {690    const counterStore = counterStoreCreator()691692    renderCounterWithContext(counterStore)693694    expect(counterStore.getState().count).toBe(1)695    expect(696      await screen.findByRole('button', { name: /one up/i }),697    ).toBeInTheDocument()698  })699700  test('should increase count by clicking a button', async () => {701    const user = userEvent.setup()702    const counterStore = counterStoreCreator()703704    renderCounterWithContext(counterStore)705706    expect(counterStore.getState().count).toBe(1)707708    await user.click(await screen.findByRole('button', { name: /one up/i }))709710    expect(counterStore.getState().count).toBe(2)711  })712})713714const renderCounterWithContext = (store) => {715  return render(<CounterWithContext />, {716    wrapper: ({ children }) => (717      <CounterStoreContext.Provider value={store}>718        {children}719      </CounterStoreContext.Provider>720    ),721  })722}723```724725## References726727- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)728  is a very lightweight solution for testing React components. It provides utility functions on top729  of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its730  primary guiding principle is: "The more your tests resemble the way your software is used, the731  more confidence they can give you."732- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)733  is a very lightweight solution for testing React Native components, similarly to RTL, but its734  functions are built on top of `react-test-renderer`.735- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid736  [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).737738## Demos739740- Jest: https://stackblitz.com/edit/jest-zustand741- Vitest: https://stackblitz.com/edit/vitest-zustand