How do I reset Redux between tests?


Has anyone been able to clear Redux between tests? What did you do?

I have a React Native Expo app using Redux.

I have a test that works in isolation, but when I run all tests, it fails because there are state changes left in redux from other tests.

How do I ‘flush’ the redux store between tests.

I tried the mock-redux-store package, but when I passed a combineReducers() to it, it returned nothing.

I could rebuild the state slices in there manually, and pass them to the mock store but that would be hard to maintain.

testing-library-utils.js :

//This file adds a Redux Provider to a component's context when running Jest tests from test files.
//This first import enables jest native, which enables some state-centric matchers
import '@testing-library/jest-native/extend-expect';
import React from 'react';
import { render } from '@testing-library/react-native';
import { Provider, combineReducers, applyMiddleware, compose } from 'redux';
import ReduxThunk from 'redux-thunk';
import { createMockStore } from 'redux-test-utils';
// import { store } from '../App';

import logBooksReducer from '../store/reducers/logBooks-reducer';
import authReducer from '../store/reducers/auth-reducer';

const composedMiddleWare = compose(applyMiddleware(ReduxThunk));

const rootReducer = combineReducers({
  logBooks: logBooksReducer,
  auth: authReducer,
});

const store = createMockStore(rootReducer, composedMiddleWare);

console.log('STORE ', JSON.stringify(store.getState()));

const AllTheProviders = ({ children }) => {
  console.log('Store.getState() from UTILS ', store.getState());
  return <Provider store={store}>{children}</Provider>;
};

const customRender = (ui, options) =>
  render(ui, { wrapper: AllTheProviders, ...options });

// re-export everything
export * from '@testing-library/react-native';

// override render method
export { customRender as render };

Source: React – Stack Overflow

November 26, 2021
Category : News
Tags: expo | javascript | react native | reactjs | redux

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.