Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: update testing #1550

Merged
merged 1 commit into from
Jan 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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