3

I'm using zustand and jest - but have been running into some trouble with tests polluting each other. So I'm trying to reset the states/stores between each test. But I notice some issues between my test suites that could only be solved by yarn jest --runInBand

I'm resetting the store like this:

import { act } from '@testing-library/react-native'
const actualCreate = jest.requireActual('zustand')

// 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) => {
  const store = actualCreate.default(createState)
  const initialState = store.getState()
  storeResetFns.add(function restFn() {
    store.setState(initialState, true)
  })
  return store
}

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

export default create

The most optimal solution seems to be that the store between tests are non-mutating/"funtional programming" - so a clean new state/store is created for each tests.

Any advice would be appreciated.

Norfeldt
  • 8,272
  • 23
  • 96
  • 152

0 Answers0