Skip to content

Commit

Permalink
docs: testing for using typescript (pmndrs#1303)
Browse files Browse the repository at this point in the history
  • Loading branch information
mugi-uno authored Sep 21, 2022
1 parent b739cfd commit 77d14b1
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/guides/testing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,36 @@ The way you mock a dependency depends on your test runner/library.

In [jest](https://jestjs.io/), you can create a `__mocks__/zustand.js` and place the code in that file. If your app is using `zustand/vanilla` instead of `zustand`, then you'll have to place the above code in `__mocks__/zustand/vanilla.js`.

### TypeScript usage

If you are using zustand, as documented in [TypeScript Guide](./typescript.md), use the following code:

```tsx
import 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 =
() =>
<S,>(createState: StateCreator<S>) => {
const store = actualCreate<S>(createState)
const initialState = store.getState()
storeResetFns.add(() => store.setState(initialState, true))
return store
}

// Reset all stores after each test run
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()))
})

export default create
```

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

You should use the following code in the `__mocks__/zustand.js` file (the `__mocks__` directory should be adjacent to node_modules, placed in the same folder as node_modules, unless you configured roots to point to a folder other than the project root [jest docs: mocking node modules](https://jestjs.io/docs/manual-mocks#mocking-node-modules)):
Expand Down

0 comments on commit 77d14b1

Please sign in to comment.