Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset Redux store after each test with jest

I am using Jest to test my Redux actions, sometimes it happens that a test does something which conflicts with what other tests do. For example, I test an action called add a user so it increases the length of the store to 1, then I test another action called add and delete a user, it expects the store to be empty after the process but the store still has a user that was existed since the first test.

Is there an accepted way to reset the Redux store for a fresh start after each test?

like image 522
Amir2mi Avatar asked Oct 28 '25 03:10

Amir2mi


1 Answers

My recommendation would be to create a new Redux store for each test - not reset it. That way, your middlewares etc. also start with a clean state.

You could use something like the setupApiStore helper in the Redux Toolkit Tests.

A simplified version would look like

function setupTestStore() {
  const refObj = {}
  
  beforeEach(() => {
    const store = configureStore({ reducer })
    refObj.store = store
    refObj.Wrapper = function Wrapper({ children }: any) {
      return <Provider store={store}>{children}</Provider>
    }
  })

  return refObj
}

and in your tests

const storeRef = setupTestStore()

it('tests something', () => {
  render(<MyComponent />, { wrapper: storeRef.wrapper }
}


it('tests something with another store', () => {
  render(<MyComponent2 />, { wrapper: storeRef.wrapper }
}
like image 94
phry Avatar answered Oct 30 '25 02:10

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!