Amir M. Mohamadi
Amir M. Mohamadi

Reputation: 1522

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?

Upvotes: 4

Views: 6135

Answers (1)

phry
phry

Reputation: 44136

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 }
}

Upvotes: 4

Related Questions