Search code examples
typescriptreduxredux-toolkit

Setting up Redux Provider for Jest Testing


I am trying to setup a redux provider for Jest testing with my react app. From what I understand I need something like this

import {ReactNode} from 'react'
import {Provider} from 'react-redux'
import {store} from "../redux/reducer/store";

type PropsWithOptionalChildren<P = unknown> = P & { children?: ReactNode };
type RootState = ReturnType<typeof store>    
interface ReduxProviderProps extends PropsWithChildren {
    store: RootState,
}

const ReduxProvider = ({children, store}: ReduxProviderProps) => <Provider store={store}>{children}</Provider>

export default ReduxProvider

Which I then use like this

test("...", () => {
  const store = configureStore();
  const wrapper = ({ children }) => (
    <ReduxProvider reduxStore={store}>{children}</ReduxProvider>
  );
  ...
});

However, the compiler complains about the following line

type RootState = ReturnType<typeof store>

type [...] does not satisfy the constraint  (...args: any) => any  type [...] provides no match for the signature  (...args: any): any 

This is the store variable

export const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production',
    middleware: getDefaultMiddleware =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat(apiSlice.middleware),
});

And additional information

export const rootReducer = combineReducers({
    a: aReducer,
    b: bReducer,
    [apiSlice.reducerPath]: apiSlice.reducer,
})

const config = getPersistConfig({
    key: 'root',
    storage,
    blacklist: ['a'],
    rootReducer
})

const persistedReducer = persistReducer(config, rootReducer)

How to resolve the compiler error?


Solution

  • Try this:

    type RootState = ReturnType<typeof store.getState>;