Skip to content

Commit

Permalink
docs: update testing
Browse files Browse the repository at this point in the history
  • Loading branch information
nus3 committed Jan 18, 2023
1 parent 9cf71d2 commit 3a6deae
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions docs/guides/testing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ When running tests, the stores are not automatically reset before each test run.
Thus, there can be cases where the state of one test can affect another. To make sure all tests run with a pristine store state, you can mock `zustand` during testing and use the following code to create your store:

```jsx
import { create: actualCreate } from 'zustand'
import { create as actualCreate } from 'zustand'
// const actualCreate = jest.requireActual('zustand') // if using jest
import { act } from 'react-dom/test-utils'

// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set()

// when creating a store, we get its initial state, create a reset function and add it in the set
const create = (createState) => {
export const create = (createState) => {
const store = actualCreate(createState)
const initialState = store.getState()
storeResetFns.add(() => store.setState(initialState, true))
Expand All @@ -30,8 +30,6 @@ const create = (createState) => {
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()))
})

export default create
```

The way you mock a dependency depends on your test runner/library.
Expand All @@ -43,15 +41,15 @@ In [jest](https://jestjs.io/), you can create a `__mocks__/zustand.js` and place
If you are using zustand, as documented in [TypeScript Guide](./typescript.md), use the following code:

```tsx
import { create: actualCreate, StateCreator } from 'zustand'
import { create as actualCreate, StateCreator } from 'zustand'
// const actualCreate = jest.requireActual('zustand') // if using jest
import { act } from 'react-dom/test-utils'

// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set<() => void>()

// when creating a store, we get its initial state, create a reset function and add it in the set
const create =
export const create =
() =>
<S,>(createState: StateCreator<S>) => {
const store = actualCreate<S>(createState)
Expand All @@ -64,8 +62,6 @@ const create =
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()))
})

export default create
```

## Resetting state between tests in **react-native** and **jest**
Expand Down

0 comments on commit 3a6deae

Please sign in to comment.